BehavioralPHPverifiedVerified

Memento Pattern in PHP

Captures and externalizes an object's internal state without violating encapsulation, allowing the object to be restored to that state later.

How to Implement the Memento Pattern in PHP

1Step 1: Define the memento (snapshot)

class Memento
{
    public function __construct(
        private readonly string $state,
        private readonly \DateTimeImmutable $date,
    ) {}

    public function getState(): string { return $this->state; }
    public function getDate(): \DateTimeImmutable { return $this->date; }
}

2Step 2: Define the originator that creates and restores from mementos

class TextEditor
{
    private string $content = '';

    public function type(string $text): void
    {
        $this->content .= $text;
    }

    public function getContent(): string { return $this->content; }

    public function save(): Memento
    {
        return new Memento($this->content, new \DateTimeImmutable());
    }

    public function restore(Memento $memento): void
    {
        $this->content = $memento->getState();
    }
}

3Step 3: Implement the caretaker that manages memento history

class History
{
    /** @var Memento[] */
    private array $snapshots = [];

    public function push(Memento $memento): void
    {
        $this->snapshots[] = $memento;
    }

    public function pop(): ?Memento
    {
        return array_pop($this->snapshots);
    }
}

// Usage
$editor = new TextEditor();
$history = new History();

$editor->type('Hello ');
$history->push($editor->save());

$editor->type('World');
echo $editor->getContent(); // "Hello World"

$editor->restore($history->pop());
echo $editor->getContent(); // "Hello "

Memento Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Memento Pattern in the Real World

Think of a video game save point. When you save, the game (originator) packages your character's stats, inventory, and position into a save file (memento). The save system (caretaker) stores these files without understanding their contents. When you die and reload, the save file is handed back to the game, which restores everything exactly as it was.