Strategy Design Pattern in PHP and Laravel with Examples
What is the Strategy pattern? The Strategy pattern is a behavioral design pattern. You define a family of algorithms, put each one in its own class behind…
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.
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.
CachedLoggedUserRepository subclasses for every combination, you combine small decorators at runtime.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.
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.
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);
}
}
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()
);
}
}
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.
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.
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.
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.
What is the Strategy pattern? The Strategy pattern is a behavioral design pattern. You define a family of algorithms, put each one in its own class behind…
No comments yet