CreationalPHPverifiedVerified

Builder Pattern in PHP

Separates the construction of a complex object from its representation, allowing the same construction process to produce different results.

How to Implement the Builder Pattern in PHP

1Step 1: Define the product

class House
{
    public int $floors = 0;
    public bool $hasGarage = false;
    public bool $hasPool = false;
    public bool $hasGarden = false;

    public function describe(): string
    {
        $features = ["{$this->floors} floor(s)"];
        if ($this->hasGarage) $features[] = 'garage';
        if ($this->hasPool) $features[] = 'pool';
        if ($this->hasGarden) $features[] = 'garden';
        return 'House with ' . implode(', ', $features);
    }
}

2Step 2: Define the builder interface

interface HouseBuilder
{
    public function setFloors(int $count): static;
    public function addGarage(): static;
    public function addPool(): static;
    public function addGarden(): static;
    public function build(): House;
}

3Step 3: Implement a concrete builder with fluent API

class StandardHouseBuilder implements HouseBuilder
{
    private House $house;

    public function __construct()
    {
        $this->house = new House();
    }

    public function setFloors(int $count): static { $this->house->floors = $count; return $this; }
    public function addGarage(): static { $this->house->hasGarage = true; return $this; }
    public function addPool(): static { $this->house->hasPool = true; return $this; }
    public function addGarden(): static { $this->house->hasGarden = true; return $this; }

    public function build(): House
    {
        $result = $this->house;
        $this->house = new House(); // Reset for reuse
        return $result;
    }
}

4Step 4: Use the builder

$house = (new StandardHouseBuilder())
    ->setFloors(2)
    ->addGarage()
    ->addGarden()
    ->build();

echo $house->describe();

Builder Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Builder Pattern in the Real World

Consider ordering a custom sandwich at a deli. You tell the sandwich artist (builder) each step — bread type, protein, toppings, sauce — and they assemble it in the right order. You don’t need to know how to layer ingredients properly; you just specify what you want, and the builder hands you a finished sandwich.