Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
OOP

Factory Pattern

Centralize object creation with factory classes or factory methods.

Factory Pattern — a practical guide to factory pattern PHP with clear examples you can reuse in real projects.

OOP Tutorial Series (53/65). Prefer one article? Read the complete OOP tutorial.

Short description

Factories help when creation logic is non-trivial or when you want to return interface types.

Simple factory

class NotifierFactory {
    public static function make(string $channel): Notifier {
        return match ($channel) {
            'email' => new EmailNotifier(),
            'sms' => new SmsNotifier(),
            default => throw new InvalidArgumentException('Unknown channel'),
        };
    }
}

Leave a reply

Your email address will not be published. Required fields are marked *