Factory Pattern in PHP

Factory Pattern in PHP

The Factory pattern is a creational design pattern used to create objects without specifying the exact class of object that will be created. It provides a method to create instances of different types, simplifying object creation and promoting loose coupling in the code.


What is the Factory Pattern?

The Factory pattern provides a centralized method for creating instances of a class, making it easier to manage and extend object creation logic. It abstracts the process of object instantiation and returns an appropriate object based on provided inputs.

Key Benefits:

  • Encapsulation: Hides the complex logic of object creation.
  • Loose Coupling: The client code doesn't need to know which class to instantiate.
  • Scalability: Easy to extend with new classes without modifying existing code.

Updated Example of the Factory Pattern

interface Logger {
    public function log(string $message);
}

class FileLogger implements Logger {
    public function log(string $message) {
        echo "Logging to a file: $message\n";
    }
}

class DatabaseLogger implements Logger {
    public function log(string $message) {
        echo "Logging to a database: $message\n";
    }
}

class LoggerFactory {
    public static function createLogger(string $type): Logger {
        if ($type === 'file') {
            return new FileLogger();
        } elseif ($type === 'database') {
            return new DatabaseLogger();
        }
        throw new InvalidArgumentException("Invalid logger type");
    }
}

$logger = LoggerFactory::createLogger('file');
$logger->log("Application started.");

Output:

Logging to a file: Application started.

When to Use the Factory Pattern

  • When the exact class of an object needs to be determined at runtime.
  • When creating complex objects with dependencies.
  • When centralizing the logic for creating related objects.

Real-World Use Cases

  • Database Connections: Creating different database connection objects based on configuration.
  • Payment Gateways: Generating different payment gateway instances for processing transactions.
  • Notification Systems: Handling multiple notification channels (email, SMS, push notifications).

Best Practices

  • Keep the Factory class focused on object creation only.
  • Use Dependency Injection when possible.
  • Combine with other patterns like Singleton and Strategy for better flexibility.

Helpful Resources


Conclusion

The Factory pattern in PHP provides a structured way to create objects without tightly coupling them with the codebase. By abstracting the object creation process, it promotes cleaner, more maintainable, and flexible code. Applying the Factory pattern is particularly useful when working with multiple classes requiring similar object creation logic.

Recent blogs
Структурные паттерны в программировании

Структурные паттерны в программировании

Порождающие паттерны в программировании

Порождающие паттерны в программировании

Генераторы и итераторы в PHP

Генераторы и итераторы в PHP

Объектно-ориентированное программирование в PHP

Объектно-ориентированное программирование в PHP

Структуры данных в PHP

Структуры данных в PHP