What It Is
The Command pattern turns an action into a value: an object that knows how to execute itself — and often how to undo itself. Actions as values can be stored in lists, queued, delayed, logged, and replayed.
The moment you need undo, you need commands: something must remember what was done, to do the opposite.
Example: Typing with Undo
Every word added to the document is a command with execute() and undo(). Executed commands go into a history list — undo is simply asking the last one to reverse itself.
Actions that can reverse themselves
The typo "wrold" is removed not by special code, but by the command that added it — it alone knows exactly what to take back. array_pop pulls the last command off the history.
Output: PHP script
<?php
class Document {
/** @var string[] */
public array $words = [];
}
interface Command {
public function execute(): void;
public function undo(): void;
}
class AddText implements Command {
public function __construct(
private Document $doc,
private string $text,
) {}
public function execute(): void {
$this->doc->words[] = $this->text;
}
public function undo(): void {
array_pop($this->doc->words);
}
}
$doc = new Document();
$history = [];
foreach (["Hello", "wrold"] as $word) {
$cmd = new AddText($doc, $word);
$cmd->execute();
$history[] = $cmd;
}
echo "document: ", implode(" ", $doc->words), "\n";
// The last command knows how to take itself back.
$last = array_pop($history);
$last->undo();
echo "after undo: ", implode(" ", $doc->words), "\n";
When to Use It
Use it for undo/redo, action queues, macros, and audit logs — anywhere actions must be stored or reversed.
Skip it when actions are fire-and-forget. In PHP, a simple queued action is often just a closure in an array — the full pattern earns its keep only when undo or inspection is needed.
Pros and Cons
Pros: undo/redo becomes natural; actions can be queued, logged and replayed; new actions plug in without touching the invoker.
Cons: one class per action adds up fast; correct undo state is subtle — a command must capture everything needed to reverse itself.