Decorator Design Pattern in PHP and Laravel with Examples

Decorator Design Pattern in PHP and Laravel with Examples

The Decorator pattern is one I reach for whenever I need to add behaviour to a class without touching its code. In this article I explain what it is, why it's useful, and how I use it in plain PHP and in Laravel.

What is the Decorator pattern?

The Decorator is a structural design pattern. It lets you wrap an object in another object that implements the same interface. The wrapper forwards calls to the wrapped object and adds something before or after: logging, caching, validation, formatting and so on.

Because the decorator and the original share an interface, the rest of your code doesn't know (or care) whether it's talking to the original or a decorated version. You can also stack several decorators on top of each other.

Why use it?

  • Open/closed principle: you extend behaviour without modifying existing, tested code.
  • No inheritance explosion: instead of CachedLoggedUserRepository subclasses for every combination, you combine small decorators at runtime.
  • Single responsibility: each decorator does one job, so it's easy to read and test.
  • Flexible composition: add, remove or reorder behaviour in one place, usually where objects are built.

The trade-off: many small classes, and deep stacks of wrappers can be harder to debug. Use it where the added behaviour is genuinely optional or cross-cutting.

How it works

  1. Define an interface for the component.
  2. Write the concrete implementation.
  3. Write a decorator that implements the same interface and receives an instance of it in the constructor.
  4. In each method, call the wrapped object and add your extra behaviour.

Example 1: a notifier in plain PHP

interface Notifier
{
    public function send(string $message): void;
}

final class EmailNotifier implements Notifier
{
    public function send(string $message): void
    {
        // send an email
        echo "Email: {$message}\n";
    }
}

abstract class NotifierDecorator implements Notifier
{
    public function __construct(protected Notifier $inner) {}

    public function send(string $message): void
    {
        $this->inner->send($message);
    }
}

final class SmsNotifier extends NotifierDecorator
{
    public function send(string $message): void
    {
        parent::send($message);
        echo "SMS: {$message}\n";
    }
}

final class SlackNotifier extends NotifierDecorator
{
    public function send(string $message): void
    {
        parent::send($message);
        echo "Slack: {$message}\n";
    }
}

$notifier = new SlackNotifier(new SmsNotifier(new EmailNotifier()));
$notifier->send('Server is down');

The calling code only sees a Notifier. Which channels are used is decided where the object is assembled.

Example 2: logging decorator

final class LoggingNotifier implements Notifier
{
    public function __construct(
        private Notifier $inner,
        private \Psr\Log\LoggerInterface $logger,
    ) {}

    public function send(string $message): void
    {
        $this->logger->info('Sending notification', ['message' => $message]);
        $this->inner->send($message);
    }
}

Example 3: caching a repository in Laravel

This is the case I see most often in Laravel projects: you have a repository and want to cache its reads without mixing cache logic into the query code.

namespace App\Repositories;

use App\Models\Product;
use Illuminate\Support\Collection;

interface ProductRepository
{
    public function featured(): Collection;
}

final class EloquentProductRepository implements ProductRepository
{
    public function featured(): Collection
    {
        return Product::where('featured', true)->get();
    }
}
namespace App\Repositories;

use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Support\Collection;

final class CachedProductRepository implements ProductRepository
{
    public function __construct(
        private ProductRepository $inner,
        private Cache $cache,
    ) {}

    public function featured(): Collection
    {
        return $this->cache->remember(
            'products.featured',
            now()->addMinutes(10),
            fn () => $this->inner->featured()
        );
    }
}

Wiring it up in a service provider

use App\Repositories\CachedProductRepository;
use App\Repositories\EloquentProductRepository;
use App\Repositories\ProductRepository;

public function register(): void
{
    $this->app->bind(ProductRepository::class, function ($app) {
        return new CachedProductRepository(
            $app->make(EloquentProductRepository::class),
            $app->make('cache.store'),
        );
    });
}

Controllers type-hint ProductRepository and get the cached version automatically. To disable caching, change one binding.

Using the container's extend method

Laravel's service container has a built-in hook that fits the Decorator pattern well: extend(). It lets you wrap an already-registered service.

$this->app->bind(ProductRepository::class, EloquentProductRepository::class);

$this->app->extend(ProductRepository::class, function ($repo, $app) {
    return new CachedProductRepository($repo, $app->make('cache.store'));
});

You can call extend() several times to stack decorators, for example caching and then logging.

Where Laravel already uses similar ideas

Middleware is a close cousin: each layer wraps the next and can act before and after the request is handled. Once you see that, the Decorator pattern feels natural in Laravel code.

When to use it

  • Adding caching, logging, metrics or retries around an existing service.
  • Combining optional features at runtime instead of writing subclasses for every combination.
  • Extending a class you can't or shouldn't modify, such as one from a vendor package, as long as it has an interface.

If you only ever need one fixed behaviour, a decorator is overkill. If you need to swap the whole algorithm rather than wrap it, look at the Strategy pattern instead.

Tagged

No comments yet

Leave a comment

Security code

Comments are checked before they appear. See the privacy policy for how your data is used.