Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 147 ยท Modern PHP and Ecosystem

Design Patterns in PHP

Learn the design patterns PHP developers really use - factory, strategy, observer, decorator, adapter, repository and DI containers - and why to avoid singletons.

A design pattern is a named, proven solution to a problem that keeps coming up in software design. "Wrap the object to add caching" or "pick one of several algorithms at runtime" are problems every developer meets; patterns give the solutions names, like decorator and strategy, so a team can discuss a design in one word instead of a whiteboard session.

Patterns aren't libraries or rules. They're shapes for your classes and interfaces, and each one has a cost: more types and more indirection. The skill is recognizing when a pattern removes real pain. This lesson covers the patterns you'll meet most in modern PHP code and frameworks, each with a small runnable example: singleton (and why to avoid it), factory, strategy, observer, decorator, adapter, repository and the dependency injection container that ties them together.

The examples build on interfaces, enums and the ideas in OOP Design Principles, especially "depend on interfaces" and "composition over inheritance".

Singleton, and why to avoid it

A singleton is a class that allows only one instance and gives global access to it through a static method. You'll find it in a lot of older PHP code, usually for the database connection or the configuration:

PHP A classic singleton

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

There is exactly one Config object (bool(true)), and that's the problem. renderFooter() looks like it has no dependencies, but it secretly reads global state. One piece of code changing the singleton changes the result everywhere else, which is why the footer suddenly says "Changed in a test". Tests can't easily give it a different configuration, and the order tests run in starts to matter.

The modern alternative is simple: create one instance at application start and pass it to the code that needs it, usually through the constructor. You still have a single object, but the dependency is visible and replaceable. A dependency injection container (at the end of this lesson) automates the passing. Static state has the same issues in general (Static Properties and Methods).

Factory

A factory is code whose job is to create objects, so the code that uses them doesn't need to know which concrete class to build or how. In PHP you'll see two common forms: static named constructors on the class itself (Money::fromString('9.99'), covered in Static Properties and Methods), and a factory method or class that picks one of several implementations:

PHP A factory that picks the implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The calling code only knows the Notifier interface and the user's preference. All knowledge about which class to create, and with which constructor arguments, lives in one place. Because match on an enum must cover every case or throw, adding Channel::Push without updating the factory fails loudly with an UnhandledMatchError instead of silently doing nothing.

Strategy

The strategy pattern puts each variant of an algorithm in its own class behind a shared interface, and lets you choose the variant at runtime. It replaces long if/switch chains that grow every time the business adds a rule. Shipping costs are a classic example:

PHP Interchangeable shipping strategies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Checkout never changes when you add a strategy. Each rule is small and testable on its own, and strategies can even wrap each other, as FreeAbove wraps ByWeight. In PHP, a very small strategy doesn't always need a class: passing a closure (callable or a Closure type) works well too, which is exactly what usort() does with its comparison function (Anonymous Functions and Closures).

Observer

The observer pattern lets an object announce that something happened without knowing who cares. Listeners subscribe to an event; when it's dispatched, each listener runs. This keeps the core action (placing an order) separate from its side effects (email, stock updates, analytics). Frameworks build their event systems on this idea, and PSR-14 standardizes the dispatcher interface (Coding Standards and PSRs):

PHP A small event dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The order numbers are random, so they change on every run, but the pattern doesn't: both orders get a confirmation email and only the 150.00 order triggers the alert. OrderService doesn't know either listener exists. Adding a new reaction means adding a listener, not editing the service. The trade-off is that the flow is harder to follow: reading place() no longer tells you everything that happens, so keep listeners for genuine side effects. PHP's SPL also ships SplSubject and SplObserver interfaces for the textbook form of this pattern, though event dispatchers are more common in practice.

Decorator

A decorator wraps an object that implements an interface with another object that implements the same interface, adding behavior before or after delegating to the inner one. Callers can't tell the difference. It's the go-to way to add caching, logging, retries or timing without touching the original class:

PHP Caching and logging decorators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

All three conversions log a rate, but the slow API is called only once, because CachedRates answers the second and third requests. The order of wrapping matters: here logging is outside the cache, so every request is logged; swap them and only cache misses would be. Decorators follow the open/closed principle: SlowApiRates never changed.

Adapter

An adapter makes a class with the "wrong" interface fit the interface your code expects. You'll need one whenever you integrate a third-party library or an old part of the system whose method names and data shapes differ from yours. The adapter translates calls in one direction and results in the other:

PHP Adapting a third-party client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The rest of the application speaks only PaymentGateway: integer cents, lowercase currency in, a simple array out. If the company switches payment providers, you write a new adapter and nothing else changes. Adapters also make testing easy: a fake PaymentGateway replaces the real one in tests (Testing PHP Code).

Repository

A repository hides how objects are stored behind a collection-like interface: find(), save(), ofCustomer(). Business code asks the repository for objects and never writes SQL itself. You built one in CRUD with PDO; the pattern is mostly about the interface:

PHP
<?php
interface OrderRepository
{
    public function find(int $id): ?Order;

    /** @return list<Order> */
    public function recentForCustomer(int $customerId, int $limit = 10): array;

    public function save(Order $order): void;
}

final class PdoOrderRepository implements OrderRepository { /* SQL lives here */ }
final class InMemoryOrderRepository implements OrderRepository { /* an array, for tests */ }

With the interface in place, production uses the PDO version and unit tests use the in-memory one. Don't let repositories grow into a dumping ground of one-off query methods; when a screen needs a special report, a dedicated query class is often clearer.

Dependency injection containers

All the patterns above lead to classes that receive their collaborators through the constructor. Someone has to build the whole object graph, and in a big application that's hundreds of objects. A dependency injection container does it for you: you tell it how to build a few things (which implementation to use for an interface, a config value), and it creates everything else, often by reading constructor types with Reflection (autowiring). PSR-11 standardizes the get()/has() interface; Laravel's container, Symfony DI and PHP-DI are well-known implementations:

PHP A tiny autowiring container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You asked for a ProfileController and never said how to build one. The container read its constructor, saw it needs a UserRepository and a Logger, built the repository (which itself needs a Logger), and used the binding for the Logger interface. The same logger instance is shared, so you get the "only one" benefit of a singleton with none of its hidden global state. Real containers add scalar config parameters, non-shared bindings, compilation for speed and good error messages, but the core is what you see here.

Don't pass the container itself into your classes and call $container->get() inside them. That's the service locator anti-pattern: dependencies become hidden again, exactly like a singleton. Ask for what you need in the constructor and let the container do the wiring from outside.

Choosing a pattern

Problem Pattern
Creating the right object depends on input or config Factory (or a static named constructor)
Several interchangeable algorithms or rules Strategy (or a closure)
Many reactions to one event, added independently Observer / event dispatcher
Add caching, logging or retries without editing a class Decorator
A library's interface doesn't match yours Adapter
Keep SQL out of business logic Repository
Build a large object graph Dependency injection container

Reach for a pattern when you feel the pain it solves, not before. Three if branches don't need a strategy hierarchy; the tenth one probably does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main problem with a singleton like Config::getInstance() used throughout an application?

    Any code can reach the instance and change it, and functions that use it look dependency-free. Creating one instance and passing it in keeps the single instance but makes the dependency visible.
  2. 2. A decorator CachedRates wraps SlowApiRates. What must be true about both classes?

    A decorator implements the same interface as the object it wraps and delegates to it, adding behavior around the call. It uses composition, not inheritance.
  3. 3. Your app's code calls PaymentGateway::charge(int $cents), but the new provider's SDK offers makePayment(float $amount). Which pattern fits?

    An adapter implements the interface your code expects and translates each call (and its result) to the interface the library provides.
  4. 4. In the lesson's container, what is autowiring?

    The container inspects the constructor, resolves each typed parameter (using bindings for interfaces) and passes the results to the new instance.
  5. 5. Which design replaces a growing switch over shipping methods inside Checkout?

    The strategy pattern puts each variant behind one interface, so new rules are new classes and Checkout itself never changes.

Summary

  • Design patterns are named solutions to recurring design problems; use one when it removes real pain, since each adds types and indirection.
  • Singletons hide global state; create one instance and pass it in instead.
  • Factories centralize object creation; match on an enum makes them exhaustive.
  • Strategy swaps algorithms behind an interface (or a closure); observer lets independent listeners react to events (PSR-14).
  • Decorator adds behavior like caching or logging by wrapping an object with the same interface; adapter translates a foreign interface into yours.
  • Repository keeps storage details behind a collection-like interface, with an in-memory version for tests.
  • A DI container builds object graphs, often by autowiring constructor types with Reflection. Inject dependencies through constructors; don't use the container as a service locator.

Next: PHP Frameworks and CMSs