PHP
The Factory pattern
Learn to move object creation to a central factory method.
What does the Factory pattern do?
The Factory pattern moves object creation to a central place. Instead of writing concrete class names with new, the client calls a createProduct method and does not need to know which concrete class is produced.
All products implement a common Product interface; concrete products have names like ConcreteProductA and ConcreteProductB. New product types can be added without touching client code.
Simple Factory: class selection with switch
In a simple Factory, a single class picks which concrete class to produce with a switch or match expression. The call uses a string key like Factory::createProduct('a'); the result is a Product instance.
PHP's match expression is short and returns a value, so it fits Factory well. The default arm throws on unknown keys, catching bad calls.
Exercise Create a product with Factory and print its name
Write a Product interface (with a name(): string method). Have ConcreteProductA and ConcreteProductB implement it; A returns 'Product A', B returns 'Product B'. Call Factory::createProduct('a') and print the product name.
Show example solution
string; }. ConcreteProductA returns 'Product A', ConcreteProductB returns 'Product B'. Get an instance with Factory::createProduct('a') and print ->name().
Example solution:
<?php
interface Product {
public function name(): string;
}
class ConcreteProductA implements Product {
public function name(): string { return 'Product A'; }
}
class ConcreteProductB implements Product {
public function name(): string { return 'Product B'; }
}
class Factory {
public static function createProduct(string $type): Product {
return match ($type) {
'a' => new ConcreteProductA(),
'b' => new ConcreteProductB(),
default => throw new \InvalidArgumentException('unknown'),
};
}
}
$p = Factory::createProduct('a');
echo $p->name();
Test yourself
-
The producing method name
<?php
class Factory {
public static function ____(string $type): Product {
return match ($type) {
'a' => new ConcreteProductA(),
'b' => new ConcreteProductB(),
};
}
}
Show answer
<?php
class Factory {
public static function createProduct(string $type): Product {
return match ($type) {
'a' => new ConcreteProductA(),
'b' => new ConcreteProductB(),
};
}
}
-
What type of value does Factory::createProduct('a') return?
- A string
- An array of class names
- A Product instance (object)
- An integer
Show answer
A Product instance (object) — Correct. createProduct returns a Product instance (object), not a class name.
-
Match the Factory concepts
- Product
- common interface
- ConcreteProductA
- concrete product A
- ConcreteProductB
- concrete product B
- createProduct
- creates an instance
Next lesson: The Observer pattern