Factory Design Pattern in PHP and Laravel with Examples

Factory Design Pattern in PHP and Laravel with Examples

What is the Factory pattern?

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.

Why use it?

  • One place for creation logic. If building an object needs configuration, dependencies or conditions, that logic lives in one spot instead of being copied around.
  • Less coupling. Your code depends on an interface, not on concrete classes.
  • Easier to extend. Adding a new type means adding a class and one line in the factory, not editing every caller.
  • Easier to test. You can swap the factory or what it returns with a fake.

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.

How to use it

  1. Define an interface for the product.
  2. Write concrete classes that implement it.
  3. Write a factory that takes some input (a type, a config value) and returns the right implementation.
  4. Let the rest of your code depend only on the interface and the factory.

A plain PHP example

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.

Factory in Laravel

Using the service container

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.

An injectable factory class

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.

Factories Laravel already uses

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.
  • Model factories (User::factory()->create()) build test data. They share the name and the idea: hide how an object is assembled.

Tips

  • Always return an interface type from the factory, not a concrete class.
  • Throw a clear exception for unknown types instead of returning null.
  • If the match keeps growing, consider mapping names to classes in a config file.
  • Factory pairs well with the Strategy pattern: the factory picks the strategy, the strategy does the work.

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.