PHP Factory Pattern
A short screencast showing how to implement a simple Factory Method in PHP.
Overview
We create three files: Product.php, Factory.php, and demo.php. The Factory class encapsulates object creation logic, avoiding duplication and making the code easier to extend.
UML diagram
Note: prefer an interface
The example above returns the concrete Product class — that is the "Simple Factory" variant. In a full Factory Method, the factory returns a ProductInterface so callers depend on an abstraction, not the concrete class. That makes swapping implementations easy:
interface ProductInterface
{
public function getInfo(): string;
}
class Product implements ProductInterface
{
public function getInfo(): string
{
return $this->type . ': ' . $this->name;
}
}
class Factory
{
public static function create(string $type, string $name): ProductInterface
{
return new Product($type, $name);
}
}
Example output
Running php demo.php in the terminal produces:
Laptop: MacBook Pro
Advantages
- Decouples client code from concrete product classes: the client uses an interface.
- The choice of class lives in one place — the factory.
- Adding a new product needs no changes in client code (open/closed principle).
- Creation is easy to replace with a fake in tests.
When to use
- When the class to instantiate is not known in advance.
- When creating an object needs non-trivial logic or configuration.
- When subclasses should decide which product is created.
- When object creation must be centralised and reused.
Usage in Laravel
In Laravel a factory method is Illuminate\Database\Connectors\ConnectionFactory: based on the configured driver it decides which connector to create (MySqlConnector, PostgresConnector, and so on). At the application level the same idea appears in model factories (Illuminate\Database\Eloquent\Factories\Factory), where definition() describes how to build a model and Model::factory() hides the concrete details.