Example of Factory Pattern in PHP
A guide on the Factory Pattern in PHP with a concrete example, explaining how to implement and use this design pattern in object-oriented programming.
The Factory pattern provides a way to create objects without having to specify the exact class that needs to be instantiated. This makes the code more flexible and easier to extend when different types of objects need to be created.
<?php
// Factory Pattern in PHP
// Interface for different types of products
interface Product {
public function getType();
}
// Concrete product classes
class ProductA implements Product {
public function getType() {
return "Product A";
}
}
class ProductB implements Product {
public function getType() {
return "Product B";
}
}
// Factory to create product objects
class ProductFactory {
public static function createProduct($type) {
switch ($type) {
case 'A':
return new ProductA();
case 'B':
return new ProductB();
default:
throw new Exception("Product type not found.");
}
}
}
// Using the factory to create products
try {
$productA = ProductFactory::createProduct('A');
echo $productA->getType(); // Output: Product A
$productB = ProductFactory::createProduct('B');
echo $productB->getType(); // Output: Product B
} catch (Exception $e) {
echo $e->getMessage();
}
?>
Detailed explanation:
-
interface Product
: This defines an interface for the products that the factory will create. Each product must implement thegetType()
method. -
class ProductA
andclass ProductB
: These are concrete classes representing different types of products. Both classes implement thegetType()
method to return the product type. -
class ProductFactory
: This is the factory class that contains thecreateProduct($type)
method, which creates an object based on the$type
parameter. If$type
is 'A', it creates aProductA
object, and for 'B', it createsProductB
. -
ProductFactory::createProduct('A')
: This call creates aProductA
object when 'A' is passed as the type. -
catch (Exception $e)
: This handles any exceptions in case the product type is invalid or does not exist.
PHP Version:
This code is compatible with PHP 5.0 and above.