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…
The Factory pattern is a creational design pattern. Instead of calling new directly all over your code, you ask a dedicated piece of code (the factory) to create objects for you. The caller says what it needs; the factory decides how to build it and which concrete class to return.
Usually the factory returns objects that share an interface, so the calling code never needs to know the concrete class.
It is not needed everywhere. If a class is simple and has one implementation, plain new is fine. Reach for a factory when you have several related implementations or non-trivial construction.
Say you send notifications through different channels.
interface Notifier
{
public function send(string $to, string $message): void;
}
class EmailNotifier implements Notifier
{
public function send(string $to, string $message): void
{
// send email
}
}
class SmsNotifier implements Notifier
{
public function send(string $to, string $message): void
{
// send SMS
}
}
class NotifierFactory
{
public static function make(string $channel): Notifier
{
return match ($channel) {
'email' => new EmailNotifier(),
'sms' => new SmsNotifier(),
default => throw new InvalidArgumentException("Unknown channel: $channel"),
};
}
}
$notifier = NotifierFactory::make('sms');
$notifier->send('+100000000', 'Your order has shipped.');
The calling code knows nothing about SmsNotifier. Adding a Telegram channel means one new class and one new line in the match.
In Laravel the service container often acts as a factory. You can bind the interface to a closure that decides which class to build:
// app/Providers/AppServiceProvider.php
public function register(): void
{
$this->app->bind(Notifier::class, function ($app) {
return match (config('services.notifier')) {
'sms' => $app->make(SmsNotifier::class),
default => $app->make(EmailNotifier::class),
};
});
}
Now any controller or job can type-hint Notifier and get the right implementation, with its own dependencies resolved by the container.
When the choice depends on runtime data (for example, the payment gateway a customer picked), inject a factory instead:
interface PaymentGateway
{
public function charge(int $amount): string;
}
class PaymentGatewayFactory
{
public function __construct(private Container $container) {}
public function make(string $gateway): PaymentGateway
{
return match ($gateway) {
'stripe' => $this->container->make(StripeGateway::class),
'paypal' => $this->container->make(PaypalGateway::class),
default => throw new InvalidArgumentException("Unsupported gateway: $gateway"),
};
}
}
class CheckoutController
{
public function pay(Request $request, PaymentGatewayFactory $factory)
{
$gateway = $factory->make($request->input('gateway'));
$transactionId = $gateway->charge($request->integer('amount'));
// ...
}
}
Here Container is Illuminate\Contracts\Container\Container.
You use factories in Laravel every day, maybe without noticing:
Cache::store('redis') and Storage::disk('s3') are created by manager classes that build the right driver from a name.Validator::make(...) is a factory method returning a configured validator.User::factory()->create()) build test data. They share the name and the idea: hide how an object is assembled.null.match keeps growing, consider mapping names to classes in a config file.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…
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