Lesson 34 of 45 · Persistence, Flow and State
The Builder Pattern
When the constructor takes four optional arguments
The Factory lesson used Invoice::issue(), a named constructor that takes five required values and builds a complete object. That works because every input is always there. The guest's itemised statement at checkout is different. It always has a room charge, and it may also have a minibar line, a late checkout fee, a discount and a tourist tax, depending on the stay. The Invoice from the Factory lesson holds the net amount, the tax and the issue date for accounting. StayInvoice is the statement the guest reads, with one line per charge. The first version has one constructor with a nullable parameter per optional part:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exceptions\MismatchedCurrencies;
use App\Reservations\ReservationId;
use DomainException;
final readonly class StayInvoice
{
public function __construct(
public ReservationId $reservationId,
public Money $roomCharge,
public ?Money $minibar = null,
public ?Money $lateCheckout = null,
public ?Money $discount = null,
public ?Money $touristTax = null,
) {
if ($discount !== null && !$discount->currency->equals($roomCharge->currency)) {
throw new MismatchedCurrencies($roomCharge->currency, $discount->currency);
}
if ($discount !== null && $discount->amountInCents > $this->subtotal()->amountInCents) {
throw new DomainException('A discount cannot be larger than the charges it applies to');
}
}
public function subtotal(): Money
{
$subtotal = $this->roomCharge;
foreach ([$this->minibar, $this->lateCheckout, $this->touristTax] as $charge) {
if ($charge !== null) {
$subtotal = $subtotal->add($charge);
}
}
return $subtotal;
}
public function total(): Money
{
if ($this->discount === null) {
return $this->subtotal();
}
return Money::fromCents(
$this->subtotal()->amountInCents - $this->discount->amountInCents,
$this->roomCharge->currency,
);
}
}ReservationId is the identifier from the Named Constructors lesson and Money is the value object from the Value Objects lesson. The constructor is correct, and the call sites are the problem. A test for a checkout with only a tourist tax reads like this:
<?php
declare(strict_types=1);
namespace Tests\Unit\Billing;
use App\Billing\Currency;
use App\Billing\Money;
use App\Billing\StayInvoice;
use App\Reservations\ReservationId;
use PHPUnit\Framework\TestCase;
final class StayInvoiceTest extends TestCase
{
public function test_the_total_adds_the_tourist_tax(): void
{
$usd = Currency::usd();
$invoice = new StayInvoice(
ReservationId::next(),
Money::fromCents(42000, $usd),
null,
null,
null,
Money::fromCents(1500, $usd),
);
$this->assertSame(43500, $invoice->total()->amountInCents);
}
}Three null arguments in a row tell the reader nothing. Named arguments help (touristTax: Money::fromCents(1500, $usd)), but the caller still decides everything in one expression, and the code that decides which lines apply cannot do it step by step. It has to collect every answer first and then call the constructor once.
A builder collects the parts one at a time
The Builder pattern moves that assembly into its own object. The caller gives the required parts first, adds optional parts as it learns about them, and calls build() once. The ReservationCart in the Immutable Objects lesson is a mutable builder: addRoom() changes the cart in place and finalize() hands back an immutable result. The builder here does the same for an invoice, but it is immutable itself, so each with* method returns a changed clone:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
final class StayInvoiceBuilder
{
private ?Money $minibar = null;
private ?Money $lateCheckout = null;
private ?Money $discount = null;
private ?Money $touristTax = null;
private function __construct(
private readonly ReservationId $reservationId,
private readonly Money $roomCharge,
) {}
public static function forStay(ReservationId $reservationId, Money $roomCharge): self
{
return new self($reservationId, $roomCharge);
}
public function withMinibar(Money $charge): self
{
$clone = clone $this;
$clone->minibar = $charge;
return $clone;
}
public function withLateCheckout(Money $fee): self
{
$clone = clone $this;
$clone->lateCheckout = $fee;
return $clone;
}
public function withDiscount(Money $discount): self
{
$clone = clone $this;
$clone->discount = $discount;
return $clone;
}
public function withTouristTax(Money $tax): self
{
$clone = clone $this;
$clone->touristTax = $tax;
return $clone;
}
public function build(): StayInvoice
{
return new StayInvoice(
$this->reservationId,
$this->roomCharge,
$this->minibar,
$this->lateCheckout,
$this->discount,
$this->touristTax,
);
}
}The reservation id and the room charge are required, so they go through forStay(), which is a named constructor. Nobody can get a builder without them. Only the optional parts get a with* method. A handler that decides which lines apply now reads as a sequence of decisions. Each part comes from a different lookup, and StayCharges is the interface in front of them. roomChargeFor() always returns a Money. The other methods cover the minibar system, the front desk's late checkout, the promotions table and the tax rules, and each returns null when the stay has none:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
interface StayCharges
{
public function roomChargeFor(ReservationId $reservationId): Money;
public function minibarFor(ReservationId $reservationId): ?Money;
public function lateCheckoutFeeFor(ReservationId $reservationId): ?Money;
public function discountFor(ReservationId $reservationId): ?Money;
public function touristTaxFor(ReservationId $reservationId): ?Money;
}The handler asks for each charge and adds only the ones that exist:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
final readonly class PrepareStayInvoiceHandler
{
public function __construct(private StayCharges $charges) {}
public function handle(ReservationId $reservationId): StayInvoice
{
$builder = StayInvoiceBuilder::forStay($reservationId, $this->charges->roomChargeFor($reservationId));
$minibar = $this->charges->minibarFor($reservationId);
if ($minibar !== null) {
$builder = $builder->withMinibar($minibar);
}
$lateCheckout = $this->charges->lateCheckoutFeeFor($reservationId);
if ($lateCheckout !== null) {
$builder = $builder->withLateCheckout($lateCheckout);
}
$discount = $this->charges->discountFor($reservationId);
if ($discount !== null) {
$builder = $builder->withDiscount($discount);
}
$touristTax = $this->charges->touristTaxFor($reservationId);
if ($touristTax !== null) {
$builder = $builder->withTouristTax($touristTax);
}
return $builder->build();
}
}The builder holds the invoice in progress while each answer comes in, and the handler never has to line up six positional arguments. Each if reassigns $builder, because the with* methods return a new builder and leave the old one alone. Calling $builder->withMinibar($minibar); without the assignment silently drops the line. That is the price of immutability here, and it is the same price DateRange charged in the Immutable Objects lesson.
Why build() is the only exit
The builder never hands out a half-assembled invoice. The only way to get a StayInvoice from it is build(), and build() goes through the StayInvoice constructor, which checks that the discount uses the room charge's currency and is not larger than the charges. The rule lives in the object, not in the builder. Someone who writes new StayInvoice(...) directly hits the same check.
Because each with* method returns a clone, one half-built builder can start several invoices without them affecting each other. This test builds two invoices from the same base, one with the minibar and one without:
<?php
declare(strict_types=1);
namespace Tests\Unit\Billing;
use App\Billing\Currency;
use App\Billing\Money;
use App\Billing\StayInvoiceBuilder;
use App\Reservations\ReservationId;
use PHPUnit\Framework\TestCase;
final class StayInvoiceBuilderTest extends TestCase
{
public function test_one_half_built_builder_can_start_two_different_invoices(): void
{
$usd = Currency::usd();
$base = StayInvoiceBuilder::forStay(ReservationId::next(), Money::fromCents(42000, $usd));
$withMinibar = $base->withMinibar(Money::fromCents(1800, $usd))->build();
$withoutMinibar = $base->build();
$this->assertSame(43800, $withMinibar->total()->amountInCents);
$this->assertSame(42000, $withoutMinibar->total()->amountInCents);
}
}If withMinibar() changed the builder in place, $base->build() would include the minibar and both totals would be 43800.
This is the property that separates a builder from a bag of setters. The caller can add parts in any order, skip the optional ones, and still cannot end up holding an invoice that breaks its own rules.
Builders you already use
Laravel's HTTP client is a builder. Http::withHeaders() goes through the factory's __call, which creates a PendingRequest and calls withHeaders() on it. That method merges the headers into the request options and returns $this. Nothing is sent until a terminal call such as get() or post().
The query builder in Illuminate\Database\Query\Builder has the same shape. where() records a condition and returns $this, and nothing runs until get(). Both mutate themselves as you chain, where StayInvoiceBuilder returns clones. The mutable version is shorter to write and surprises you when you keep a reference to a half-built query and branch from it. The query builder has a clone() method for exactly that case.
Symfony's form component says it directly. The 8.1 docs: "Symfony provides a "form builder" object which allows you to describe the form fields using a fluent interface. Later, this builder creates the actual form object used to render and process contents." You call add() on a FormBuilderInterface, then getForm().
Builder, factory, named constructor
The three solve different problems:
A named constructor builds an object from inputs the caller already has, in one call.
A factory builds an object when construction needs services or a runtime decision, such as the next invoice number or the tax rate for a room.
A builder assembles an object over several calls when many parts are optional or are decided at different times.
They also combine. forStay() is a named constructor on a builder, and a factory can hand out a builder that is already seeded with the number and tax rate it fetched from its services.
What the Gang of Four described
The fluent builder in this lesson is the version PHP code uses most, and it is not quite the pattern in the book. The Gang of Four state the intent as: "Separate the construction of a complex object from its representation so that the same construction process can create different representations." That shape has a Director that knows the order of the building steps and a Builder interface with several concrete builders. The same Director can drive a builder that makes a PDF model and another that makes an email body.
The same shape for the stay invoice starts with a StayInvoiceSteps interface that lists the building steps:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
interface StayInvoiceSteps
{
public function addRoomCharge(ReservationId $reservationId, Money $charge): void;
public function addMinibar(Money $charge): void;
public function addLateCheckout(Money $fee): void;
public function addDiscount(Money $discount): void;
public function addTouristTax(Money $tax): void;
}StayInvoiceDirector reads StayCharges in a fixed order and calls the steps. It never knows which representation it is building:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
final readonly class StayInvoiceDirector
{
public function __construct(private StayCharges $charges) {}
public function construct(ReservationId $reservationId, StayInvoiceSteps $steps): void
{
$steps->addRoomCharge($reservationId, $this->charges->roomChargeFor($reservationId));
$minibar = $this->charges->minibarFor($reservationId);
if ($minibar !== null) {
$steps->addMinibar($minibar);
}
$lateCheckout = $this->charges->lateCheckoutFeeFor($reservationId);
if ($lateCheckout !== null) {
$steps->addLateCheckout($lateCheckout);
}
$discount = $this->charges->discountFor($reservationId);
if ($discount !== null) {
$steps->addDiscount($discount);
}
$touristTax = $this->charges->touristTaxFor($reservationId);
if ($touristTax !== null) {
$steps->addTouristTax($touristTax);
}
}
}PdfInvoiceBuilder collects lines for a PdfInvoiceModel, and EmailInvoiceBuilder collects text. getResult() sits on each concrete builder, not on StayInvoiceSteps, because the two products have different types: a PdfInvoiceModel and a string. The Gang of Four give the same reason for having no common parent class for products. Concrete builders are also mutable, so each one is single-use: create a new builder for every construct() call, or the second run adds its lines to the first. They also skip the rules StayInvoice checks. A discount larger than the charges gets no DomainException here: getResult() fails with Money's "Money cannot be negative" error instead. The output is only as valid as what StayCharges returns:
<?php
declare(strict_types=1);
namespace App\Billing;
final readonly class PdfInvoiceModel
{
/**
* @param array<string, string> $lines label => formatted amount
*/
public function __construct(
public string $reservation,
public array $lines,
public string $total,
) {}
}<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
final class PdfInvoiceBuilder implements StayInvoiceSteps
{
private string $reservation = '';
/** @var array<string, string> */
private array $lines = [];
private ?Money $subtotal = null;
private ?Money $discount = null;
public function addRoomCharge(ReservationId $reservationId, Money $charge): void
{
$this->reservation = $reservationId->value;
$this->addLine('Room', $charge);
}
public function addMinibar(Money $charge): void
{
$this->addLine('Minibar', $charge);
}
public function addLateCheckout(Money $fee): void
{
$this->addLine('Late checkout', $fee);
}
public function addDiscount(Money $discount): void
{
$this->discount = $discount;
$this->lines['Discount'] = '-' . $discount->format();
}
public function addTouristTax(Money $tax): void
{
$this->addLine('Tourist tax', $tax);
}
public function getResult(): PdfInvoiceModel
{
$total = $this->subtotal;
if ($total !== null && $this->discount !== null) {
$total = Money::fromCents(
$total->amountInCents - $this->discount->amountInCents,
$total->currency,
);
}
return new PdfInvoiceModel($this->reservation, $this->lines, $total?->format() ?? '');
}
private function addLine(string $label, Money $amount): void
{
$this->lines[$label] = $amount->format();
$this->subtotal = $this->subtotal?->add($amount) ?? $amount;
}
}<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
final class EmailInvoiceBuilder implements StayInvoiceSteps
{
/** @var list<string> */
private array $lines = [];
public function addRoomCharge(ReservationId $reservationId, Money $charge): void
{
$this->lines[] = "Your invoice for reservation {$reservationId->value}";
$this->lines[] = "Room: {$charge->format()}";
}
public function addMinibar(Money $charge): void
{
$this->lines[] = "Minibar: {$charge->format()}";
}
public function addLateCheckout(Money $fee): void
{
$this->lines[] = "Late checkout: {$fee->format()}";
}
public function addDiscount(Money $discount): void
{
$this->lines[] = "Discount: -{$discount->format()}";
}
public function addTouristTax(Money $tax): void
{
$this->lines[] = "Tourist tax: {$tax->format()}";
}
public function getResult(): string
{
return implode("\n", $this->lines);
}
}One test runs the director with both builders:
<?php
declare(strict_types=1);
namespace Tests\Unit\Billing;
use App\Billing\Currency;
use App\Billing\EmailInvoiceBuilder;
use App\Billing\Money;
use App\Billing\PdfInvoiceBuilder;
use App\Billing\StayCharges;
use App\Billing\StayInvoiceDirector;
use App\Reservations\ReservationId;
use PHPUnit\Framework\TestCase;
final class StayInvoiceDirectorTest extends TestCase
{
public function test_the_same_director_builds_a_pdf_model_and_an_email_body(): void
{
$usd = Currency::usd();
$reservationId = ReservationId::next();
$director = new StayInvoiceDirector(new class ($usd) implements StayCharges {
public function __construct(private readonly Currency $usd) {}
public function roomChargeFor(ReservationId $reservationId): Money
{
return Money::fromCents(42000, $this->usd);
}
public function minibarFor(ReservationId $reservationId): ?Money
{
return Money::fromCents(1800, $this->usd);
}
public function lateCheckoutFeeFor(ReservationId $reservationId): ?Money
{
return null;
}
public function discountFor(ReservationId $reservationId): ?Money
{
return null;
}
public function touristTaxFor(ReservationId $reservationId): ?Money
{
return Money::fromCents(1500, $this->usd);
}
});
$pdf = new PdfInvoiceBuilder();
$email = new EmailInvoiceBuilder();
$director->construct($reservationId, $pdf);
$director->construct($reservationId, $email);
$this->assertSame('$453.00', $pdf->getResult()->total);
$this->assertSame('$420.00', $pdf->getResult()->lines['Room']);
$this->assertStringContainsString('Minibar: $18.00', $email->getResult());
$this->assertStringContainsString('Tourist tax: $15.00', $email->getResult());
}
}A StayInvoiceBuilder has no Director and one product, because the caller is the director and there is one representation. What the two share is the part that matters day to day: an object is assembled step by step and handed over only when complete. With only one representation, the interface, director and second builder are ceremony. The two builders above are what it costs to support a second one.
Builders in tests
Test data is a common place to meet this pattern. A test needs a Reservation and cares about one field, and a builder with defaults for the rest keeps the test short. The test doubles lesson builds a ReservationBuilder for that purpose. It names most of its methods for the test, forRoom() and checkingInOn(), and keeps withStatus() for the rest, but the shape is the one shown here: each method returns a changed clone, build() is the only exit, and defaults stand in for required constructor arguments.
Pitfalls
A builder for a three-field object. If a constructor takes three required values, a builder only adds a class. Use a constructor or a named constructor. A builder pays off once optional parts pile up or the parts arrive at different times.
A build() that can return an invalid object. A builder that stores parts and passes them along unchecked moves the bug from the call site to wherever the object is used. Put the rules in the object's constructor so build() cannot skip them, as StayInvoice does.
Builder setters leaking into the domain. A StayInvoice with setMinibar() methods so that "the builder is not needed" gives up the guarantee that a finished invoice does not change. The builder exists so the invoice can stay immutable. If other code starts asking the builder for state or reusing it as a model, it has become a second invoice class.
The one thing to remember
A builder collects optional parts one step at a time and hands back a complete, valid object from build(). Required parts stay in the constructor, and the rules stay in the object.
Related Links
- Builder (Refactoring.Guru)Explains the Builder pattern step by step, including the optional Director that fixes the order of the building steps.
- Builder (SourceMaking)States the intent of Builder and shows the Director and Builder roles.
- HTTP Client (Laravel Docs)Shows the fluent request builder, including withHeaders, that sends nothing until a terminal call such as get or post.
- Forms (Symfony Docs)Shows the form builder, where fields are added through a fluent interface before the form is created.