The Simple Factory Pattern is a creational design pattern that provides a unified way to create objects. Using object-oriented programming in PHP, we can implement the Simple Factory Pattern to dynamically create objects with ease.
In the Simple Factory Pattern, the Factory class is responsible for creating objects. The factory class typically contains a static method that decides which object to create based on the passed parameter. This allows us to create the necessary objects by calling the static method of the factory class without directly instantiating specific objects.
Let’s take a Product class as an example to demonstrate how to implement dynamic object creation using PHP object-oriented simple factory pattern.
// Product class
class Product {
private $name;
private $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
// Factory class
class ProductFactory {
public static function createProduct($type) {
switch ($type) {
case 'book':
return new Product('Book', 29.99);
case 'phone':
return new Product('Phone', 499.99);
case 'laptop':
return new Product('Laptop', 999.99);
default:
throw new Exception('Unsupported product type: ' . $type);
}
}
}
// Using the factory class to create product objects
$book = ProductFactory::createProduct('book');
$phone = ProductFactory::createProduct('phone');
$laptop = ProductFactory::createProduct('laptop');
echo $book->getName(); // Output: Book
echo $book->getPrice(); // Output: 29.99
echo $phone->getName(); // Output: Phone
echo $phone->getPrice(); // Output: 499.99
echo $laptop->getName(); // Output: Laptop
echo $laptop->getPrice(); // Output: 999.99
Through the example above, we demonstrated how to use the PHP object-oriented Simple Factory Pattern to implement dynamic object creation. Using the factory class, we can create different product objects based on the type. When we need to add new product types, we can simply extend the factory class with new cases, without modifying other parts of the code.
Using the Simple Factory Pattern improves code extensibility and maintainability, making the code clearer and easier to manage. It also decouples the creation process, making it easier to modify and optimize later on.