How can a Factory design pattern be implemented to handle the creation of classes in PHP?
The Factory design pattern can be implemented in PHP to handle the creation of classes by defining a Factory class that contains a method for creating instances of different classes based on a specified parameter. This allows for centralized creation logic and promotes flexibility and scalability in the codebase.
<?php
// Define an interface for the classes to be created
interface Product {
public function getName();
}
// Concrete implementation of the Product interface
class ConcreteProductA implements Product {
public function getName() {
return "Product A";
}
}
// Concrete implementation of the Product interface
class ConcreteProductB implements Product {
public function getName() {
return "Product B";
}
}
// Factory class for creating instances of different classes
class ProductFactory {
public static function createProduct($type) {
switch ($type) {
case 'A':
return new ConcreteProductA();
case 'B':
return new ConcreteProductB();
default:
throw new Exception("Invalid product type");
}
}
}
// Usage of the Factory pattern
$productA = ProductFactory::createProduct('A');
echo $productA->getName(); // Output: Product A
$productB = ProductFactory::createProduct('B');
echo $productB->getName(); // Output: Product B