Welcome back to PHP Design Patterns Game!
In our previous installment, we explored how the Decorator Pattern allows a game character to acquire additional capabilities without creating a separate class for every equipment combination.
Today, we will solve a different problem: how can a game remember player actions, undo mistakes, and replay a sequence of movements?
The Command Pattern provides an elegant solution by representing actions as objects.
The Game: Escape from the Grid
Our game takes place on a small grid. The player starts at position (0, 0) and must reach the treasure at position (2, 2).
The player can move north, south, east, or west.
We also want two additional capabilities: undoing the previous movement and replaying the recorded movement history.
Instead of calling movement methods directly from the game controller, we will encapsulate each movement inside a command object.
Understanding the Command Pattern
The Command Pattern is a behavioral design pattern that encapsulates a request as an object.
A typical implementation separates the object requesting an action from the object performing it.
In our example, the Player object is the receiver. A MoveCommand represents a movement request, while CommandHistory executes commands and remembers them.
Each command also stores the information necessary to reverse its effect.
The Complete PHP Game
The following example is compatible with PHP 8.2 and later. Save it as command-game.php.
<?php
declare(strict_types=1);
final class Player
{
private int $x = 0;
private int $y = 0;
public function position(): array
{
return [$this->x, $this->y];
}
public function move(int $dx, int $dy): bool
{
$x = $this->x + $dx;
$y = $this->y + $dy;
if ($x < 0 || $x > 4 || $y < 0 || $y > 4) {
return false;
}
$this->x = $x;
$this->y = $y;
return true;
}
public function restore(array $position): void
{
[$this->x, $this->y] = $position;
}
}
interface GameCommand
{
public function execute(): bool;
public function undo(): void;
public function description(): string;
}
final class MoveCommand implements GameCommand
{
private ?array $previous = null;
public function __construct(
private Player $player,
private string $direction
) {}
public function execute(): bool
{
if ($this->previous !== null) {
throw new LogicException(
'Command already executed'
);
}
$moves = [
'north' => [0, 1],
'south' => [0, -1],
'east' => [1, 0],
'west' => [-1, 0],
];
if (!isset($moves[$this->direction])) {
throw new InvalidArgumentException(
'Invalid direction'
);
}
[$dx, $dy] = $moves[$this->direction];
$before = $this->player->position();
if (!$this->player->move($dx, $dy)) {
return false;
}
$this->previous = $before;
return true;
}
public function undo(): void
{
if ($this->previous === null) {
throw new LogicException(
'Command not executed'
);
}
$this->player->restore($this->previous);
$this->previous = null;
}
public function description(): string
{
return $this->direction;
}
}
final class CommandHistory
{
private array $history = [];
public function run(GameCommand $command): bool
{
if (!$command->execute()) {
return false;
}
$this->history[] = $command;
return true;
}
public function undo(): bool
{
if ($this->history === []) {
return false;
}
$command = array_pop($this->history);
$command->undo();
return true;
}
public function recordedMoves(): array
{
return array_map(
fn(GameCommand $command): string
=> $command->description(),
$this->history
);
}
}
function showPosition(Player $player): void
{
[$x, $y] = $player->position();
echo "Player: ($x, $y)" . PHP_EOL;
}
$player = new Player();
$history = new CommandHistory();
foreach (['east', 'north', 'east', 'north'] as $move) {
$history->run(
new MoveCommand($player, $move)
);
}
showPosition($player);
$history->undo();
showPosition($player);
$recording = $history->recordedMoves();
$replayPlayer = new Player();
$replayHistory = new CommandHistory();
foreach ($recording as $move) {
$replayHistory->run(
new MoveCommand($replayPlayer, $move)
);
}
echo "Replay ";
showPosition($replayPlayer);
if ($player->position() !== [2, 1]) {
throw new RuntimeException(
'Undo test failed'
);
}
if ($replayPlayer->position() !== [2, 1]) {
throw new RuntimeException(
'Replay test failed'
);
}Expected Output
Player: (2, 2)
Player: (2, 1)
Replay Player: (2, 1)The player initially reaches the treasure at (2, 2).
After undoing the final northward movement, the player returns to (2, 1).
Replaying the remaining commands against a new player reproduces the same position.
What Makes This a Command Pattern?
The important architectural decision is that the history manager does not directly manipulate the player.
Instead, it executes objects implementing the GameCommand interface.
Each command knows how to perform its operation and how to reverse it.
The history manager only needs to execute commands, store successful operations, and invoke undo when requested.
This separation allows new actions to be introduced without changing the history manager.
For example, a TreasureCommand could represent collecting an item, while an AttackCommand could represent a combat action.
Undo and Replay Are Different Problems
Undo reverses the effect of a previously executed operation.
Replay executes a recorded sequence of operations again, usually against a known initial state.
These operations are related but not identical.
Our implementation records movement directions and reconstructs new command objects during replay.
This avoids reusing command objects that retain references to the original player and previous execution state.
In more complex applications, reliable replay may also require recording random seeds, timestamps, external inputs, and application-version information.
When the Pattern Becomes Too Complicated
The Command Pattern introduces additional objects and interfaces.
For a game containing only a few simple movement operations, directly calling methods may be easier to understand.
The pattern becomes more valuable when actions need to be recorded, queued, reversed, audited, or executed through different interfaces.
It is also important to recognize that not every operation can be reversed safely.
Actions involving external systems, payments, network requests, or irreversible changes may require compensating operations rather than simple undo methods.
Your Turn: Implement Redo
Our game supports undo but not redo.
Extend CommandHistory with a second stack containing undone commands.
When the player requests redo, execute the most recently undone command again and return it to the active history.
Remember that executing a new command after undoing an earlier action should normally clear the redo history.
For an additional challenge, introduce a TreasureCommand that removes treasure from the map when collected and restores it when undone.
Finally, consider whether a failed command should appear in the history. Our implementation records only successfully executed commands.
Beyond Games
The Command Pattern is useful in text editors, task-processing systems, graphical interfaces, and applications that need auditable operations.
Its central idea is simple: represent an action as an object rather than embedding its execution directly inside the code requesting it.
That additional layer of abstraction can make undo, replay, scheduling, and extensibility considerably easier to manage.
In the next PHP Design Patterns Game installment, we will explore the Builder Pattern by constructing configurable RPG characters.

















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






