Back to results for “Match”
PHP › Design Patterns in PHP

How does the Factory pattern help decouple object creation logic from the code that actually uses those objects?

Intermediate

Answer

The Factory pattern centralizes the logic for creating objects within a dedicated factory class or method, letting the rest of your code request an object without needing to know the exact concrete class or complex construction logic involved, which is especially useful when object creation depends on runtime conditions or when you want to make it easy to swap which concrete class gets created without changing the code that uses the resulting object.
class NotificationFactory {
    public static function create(string $type): NotificationInterface {
        return match ($type) {
            'email' => new EmailNotification(),
            'sms' => new SmsNotification(),
        };
    }
}
Real-world example A notification system uses a factory to decide whether to create an email or SMS notification object based on a user's stored preference, keeping that decision logic in one central place rather than scattered throughout the codebase.

Common follow-ups: What is the difference between a simple factory and the more formal Factory Method pattern?;How does the Factory pattern relate to the dependency inversion principle?