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'),
};
}
}