Welcome back to PHP Design Patterns Game, our practical series exploring software design through small, playable examples.
Today we are building a dungeon.
A dungeon room may contain enemies, treasure, traps, and an entrance. Some rooms are simple. Others require several elements to be configured before they are ready for the player.
We could create a constructor with a growing list of arguments. But as the number of options increases, object creation becomes difficult to read and maintain.
The Builder pattern offers another approach: construct a complex object through a sequence of explicit steps.
The Problem: Too Many Construction Options
Imagine creating dungeon rooms with a constructor that accepts the room name, enemy count, treasure amount, trap damage, and several additional configuration values.
A call containing many positional arguments quickly becomes difficult to interpret. Optional parameters can also produce combinations that are valid syntactically but meaningless for the game.
PHP named arguments improve readability, but they do not automatically solve the problem of constructing objects through multiple meaningful stages.
The Builder pattern separates the construction process from the final object.
Step 1: Define the Dungeon Room
Our room will be an immutable value object once construction is complete.
<?php
declare(strict_types=1);
final readonly class DungeonRoom
{
public function __construct(
public string $name,
public int $enemies,
public int $treasure,
public int $trapDamage
) {
}
public function describe(): string
{
return sprintf(
'%s: %d enemies, %d gold, trap damage %d',
$this->name,
$this->enemies,
$this->treasure,
$this->trapDamage
);
}
}PHP 8.2 supports readonly classes, allowing the completed room’s properties to remain unchanged after construction.
Step 2: Create the Builder
The builder holds temporary construction state. Its methods express the steps used to assemble a room.
final class DungeonRoomBuilder
{
private string $name = 'Unnamed Room';
private int $enemies = 0;
private int $treasure = 0;
private int $trapDamage = 0;
public function named(string $name): self
{
if (trim($name) === '') {
throw new InvalidArgumentException(
'Room name cannot be empty.'
);
}
$this->name = $name;
return $this;
}
public function withEnemies(int $count): self
{
if ($count < 0) {
throw new InvalidArgumentException(
'Enemy count cannot be negative.'
);
}
$this->enemies = $count;
return $this;
}
public function withTreasure(int $gold): self
{
if ($gold < 0) {
throw new InvalidArgumentException(
'Treasure cannot be negative.'
);
}
$this->treasure = $gold;
return $this;
}
public function withTrap(int $damage): self
{
if ($damage < 0) {
throw new InvalidArgumentException(
'Trap damage cannot be negative.'
);
}
$this->trapDamage = $damage;
return $this;
}
public function build(): DungeonRoom
{
return new DungeonRoom(
$this->name,
$this->enemies,
$this->treasure,
$this->trapDamage
);
}
}Each configuration method returns the builder itself, enabling fluent method chaining. The build() method creates a separate DungeonRoom instance.
The builder is mutable, but the completed room is not. That separation is useful when construction involves temporary decisions that should not remain available after the object is created.
Step 3: Build Two Different Rooms
Now the game can describe rooms through readable construction steps.
$treasureRoom = (new DungeonRoomBuilder())
->named('Forgotten Treasury')
->withEnemies(2)
->withTreasure(150)
->withTrap(10)
->build();
$bossRoom = (new DungeonRoomBuilder())
->named('Dragon Chamber')
->withEnemies(1)
->withTreasure(500)
->withTrap(25)
->build();
echo $treasureRoom->describe(), PHP_EOL;
echo $bossRoom->describe(), PHP_EOL;Expected output:
Forgotten Treasury: 2 enemies, 150 gold, trap damage 10
Dragon Chamber: 1 enemies, 500 gold, trap damage 25The slightly awkward phrase “1 enemies” is intentional in this minimal example: it exposes a presentation concern that should be handled separately from object construction.
Step 4: Play the Room
We can add a simple encounter function that calculates the player’s remaining health after entering a room.
function enterRoom(
DungeonRoom $room,
int $health
): int {
$enemyDamage = $room->enemies * 5;
$remaining = max(
0,
$health - $enemyDamage - $room->trapDamage
);
echo 'Entering: ', $room->name, PHP_EOL;
echo 'Health remaining: ', $remaining, PHP_EOL;
echo 'Gold discovered: ', $room->treasure, PHP_EOL;
return $remaining;
}
$health = 100;
$health = enterRoom($treasureRoom, $health);
$health = enterRoom($bossRoom, $health);With the example values, the first room reduces health from 100 to 80. The second reduces it from 80 to 50.
This is deliberately a small deterministic game. It does not include combat choices, randomness, inventory management, or persistent state.
What Makes This a Builder?
The essential distinction is that the client does not need to supply every construction detail through a single constructor call.
Instead, it uses a dedicated object to configure the desired result and requests the completed product through build().
The builder can also validate individual steps, establish defaults, and eventually enforce relationships between configuration options.
A more elaborate implementation could introduce a director that defines standard construction sequences, such as a beginner dungeon, treasure vault, or boss arena. Our example does not need that additional abstraction.
When Builder Is Worth Using
Builder becomes useful when an object has many optional components, when construction requires validation, or when the same construction process must produce several meaningful configurations.
Outside games, the pattern can help assemble complex reports, HTTP requests, configuration objects, or test fixtures.
However, Builder is not automatically superior to a constructor. For a small object with two required properties, a straightforward constructor is usually clearer.
Fluent builders also introduce mutable intermediate state. Reusing one builder across requests without resetting its properties can accidentally carry values from one object into another.
In production code, decide whether builders should be single-use, explicitly resettable, or immutable themselves.
Reader Challenge: Design a Dungeon Difficulty System
Extend the example with three predefined difficulty levels: Easy, Normal, and Hard.
Each level should configure enemy counts, treasure, and trap damage differently. Add a validation rule preventing rooms from containing more than ten enemies.
For an additional challenge, introduce a director that creates standard dungeon layouts using the existing builder.
The objective is not to write the largest possible abstraction. It is to make construction readable while keeping the resulting objects valid.

















![PHP #[Override]: Catching Broken Inheritance Contracts Before Production](https://phpmagazine.net/wp-content/uploads/2026/11/php-override-218x150.png)






