What It Is
The Memento pattern saves a snapshot of an object's state so it can be restored later — without showing the object's insides to anyone. The object itself makes the snapshot and itself restores from it; the outside world just holds the snapshots.
This is the pattern behind "undo to a saved point", drafts, and checkpoints.
Example: Editor Snapshots
save() returns a snapshot; restore() takes one back. The mistake in between simply disappears.
Save, break, restore
The snapshot was taken while the text was good. After the bad edit, restore($saved) brings the exact old state back — the holder of the snapshot never looked inside it. The snapshot is a readonly class: once made, nothing can change it.
Output: PHP script
<?php
// The memento: a frozen snapshot of the state.
final readonly class Snapshot {
public function __construct(public string $text) {}
}
class Editor {
public string $text = "";
public function save(): Snapshot {
return new Snapshot($this->text);
}
public function restore(Snapshot $snapshot): void {
$this->text = $snapshot->text;
}
}
$editor = new Editor();
$editor->text = "Hello, world!";
$saved = $editor->save();
$editor->text = "Hello, wrold! oops";
echo "now: ", $editor->text, "\n";
$editor->restore($saved);
echo "undo: ", $editor->text, "\n";
When to Use It
Use it for checkpoints and rollback: editor undo, game saves, "restore defaults", transactional steps that may need reverting.
Skip it when the state is one or two plain values — just keep the old value in a variable. And compare with Command: commands undo step by step, mementos jump back to a saved point.
Pros and Cons
Pros: real rollback without exposing internals; snapshots are simple values that can be kept in lists for multi-level undo.
Cons: snapshots of big state cost memory fast; deciding what belongs in the snapshot (and keeping it complete as the class grows) is easy to get wrong.