Example 4: Pizzas builder pattern

<?php

// Define the Pizza class
class Pizza
{
    private $sauce;

    private $cheese;

    private $toppings = [];

    public function setSauce($sauce)
    {
        $this->sauce = $sauce;
    }

    public function setCheese($cheese)
    {
        $this->cheese = $cheese;
    }

    public function addTopping($topping)
    {
        $this->toppings[] = $topping;
    }
}

class PizzaBuilder
{
    private $pizza;

    public function __construct()
    {
        $this->pizza = new Pizza();
    }

    public function addSauce($sauce)
    {
        $this->pizza->setSauce($sauce);

        return $this;
    }

    public function addCheese($cheese)
    {
        $this->pizza->setCheese($cheese);

        return $this;
    }

    public function addTopping($topping)
    {
        $this->pizza->addTopping($topping);

        return $this;
    }

    public function build()
    {
        return $this->pizza;
    }
}

Usage

$margarita = (new PizzaBuilder())
    ->addSauce('tomato')
    ->addCheese('mozzarella')
    ->build();

var_dump($margarita);

object(Pizza)#1 (3) {
    ["sauce":"Pizza":private]=>
    string(6) "tomato"
    ["cheese":"Pizza":private]=>
    string(10) "mozzarella"
 }

$prosciutto = (new PizzaBuilder())
    ->addSauce('tomato')
    ->addCheese('mozzarella')
    ->addTopping('prosciutto')
    ->addTopping('mushrooms')
    ->build();

var_dump($prosciutto);

object(Pizza)#1 (3) {
    ["sauce":"Pizza":private]=>
    string(6) "tomato"
    ["cheese":"Pizza":private]=>
    string(10) "mozzarella"
    ["toppings":"Pizza":private]=>
    array(1) {
        [0]=>
        string(10) "prosciutto"
        [1]=>
        string(9) "mushrooms"
    }
}