Skip to main content

What It Is

The Builder pattern constructs a complex object step by step. Instead of one constructor with a long, confusing argument list, the builder offers small named steps — and a final build() that returns the finished object.

In PHP the steps return $this, so calls chain into a readable sentence.


Example: Building a Pizza

Compare (new PizzaBuilder("large"))->cheese()->topping("mushrooms") with a constructor like new Pizza("large", true, [...]) — the builder says what every value means, and optional parts are simply skipped.

Steps that chain

Every step is named and optional: the small pizza skips them all. No true, null, false argument soup — and the toppings print as a plain comma list, none when there are none.

Prompt
Write a PHP script with a PizzaBuilder: the constructor takes the size, cheese and topping steps return $this for chaining, and build returns the finished Pizza object. Build one large pizza with cheese and two toppings and one plain small pizza, printing both (toppings joined with implode, "none" when empty).
Output: PHP script

When to Use It

Use it when an object has many optional parts, or when construction has real steps that deserve names. Requests, queries, and configurations are classic builder territory.

Skip it for simple objects — PHP's named arguments, new Pizza(size: "large"), already make a plain constructor read well for the easy cases.


Pros and Cons

Pros: readable construction; optional parts without giant argument lists; the object can be validated once, in build().

Cons: a second class to write and maintain; overkill where a plain constructor already reads well.