Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
PHP

PHP

Pragmatic server-side language that powers a large share of the web.

Paradigm
OOP, procedural, functional features
Typing
Dynamic with gradual typing (strict_types)
Memory
Reference counting + cycle collector
Runs
Zend Engine, bytecode + OPcache, optional JIT
Concurrency
Shared-nothing per request; Fibers (8.1)
Behavioral pattern

Memento

Intent

Saves and restores an object's previous state without revealing its implementation.

Problem

An editor needs undo, but snapshotting requires access to private fields.

Solution

The originator produces snapshot objects itself; a caretaker stores them.

Real-world analogy

Think of it like this

Saving your game before the boss fight, so you can reload if things go wrong.

Structure

association / extends implements / depends on
Originator - state+ save(): Memento+ restore(m: Memento) 1 Memento - state+ getState() 2 Caretaker - originator- history: Memento[]+ doSomething()+ undo() 3

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Originator — Originator produces snapshots of its own state and restores from them.
  2. 2Memento — Memento is an immutable snapshot of the originator's state.
  3. 3Caretaker — Caretaker knows when to capture and restore, and keeps a history stack.

Code example

A PHP code sample for Memento is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Memento when undo / snapshots.

Use Memento when direct access to fields would break encapsulation.

Pros and cons

Pros

  • Snapshots without breaking encapsulation

Cons

  • Memory use with frequent snapshots

Relations with other patterns

Check yourself

Check yourself

A form editor must restore its previous state when the user presses Cancel.

Saved in this browser only. Part of Behavioral patterns (0/11).