CreationalPHPverifiedVerified

Factory Method Pattern in PHP

Defines an interface for creating an object but lets subclasses decide which class to instantiate. Defers instantiation to subclasses.

How to Implement the Factory Method Pattern in PHP

1Step 1: Define the product interface and concrete products

interface Transport
{
    public function deliver(string $cargo): string;
}

class Truck implements Transport
{
    public function deliver(string $cargo): string
    {
        return "Delivering '{$cargo}' by truck on road";
    }
}

class Ship implements Transport
{
    public function deliver(string $cargo): string
    {
        return "Delivering '{$cargo}' by ship across ocean";
    }
}

2Step 2: Define the creator with the factory method

abstract class Logistics
{
    // Factory method — subclasses decide which Transport to create
    abstract protected function createTransport(): Transport;

    // Business logic uses the product interface
    public function planDelivery(string $cargo): string
    {
        $transport = $this->createTransport();
        return $transport->deliver($cargo);
    }
}

3Step 3: Concrete creators override the factory method

class RoadLogistics extends Logistics
{
    protected function createTransport(): Transport
    {
        return new Truck();
    }
}

class SeaLogistics extends Logistics
{
    protected function createTransport(): Transport
    {
        return new Ship();
    }
}

4Step 4: Client code works with the creator abstraction

$logistics = new RoadLogistics();
echo $logistics->planDelivery('Electronics'); // Delivering 'Electronics' by truck on road

Factory Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Factory Method Pattern in the Real World

Think of a logistics company that ships packages. The headquarters defines the shipping process but doesn’t decide the vehicle. Regional offices (subclasses) choose whether to use trucks, ships, or drones based on local conditions. The headquarters just says ‘get me a transport’ and the regional office delivers the right one.