@ryleigh
The Memento design pattern is a behavioral pattern that allows an object's state to be saved and restored without violating encapsulation. In PHP, the Memento pattern can be implemented using the following steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Memento { private $state; public function __construct($state) { $this->state = $state; } public function getState() { return $this->state; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Originator { private $state; public function setState($state) { $this->state = $state; } public function getState() { return $this->state; } public function saveStateToMemento() { return new Memento($this->state); } public function getStateFromMemento($memento) { $this->state = $memento->getState(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Caretaker { private $mementos = []; public function addMemento($memento) { $this->mementos[] = $memento; } public function getMemento($index) { return $this->mementos[$index]; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// create Originator object $originator = new Originator(); // set state $originator->setState("State1"); // save state to Memento $caretaker = new Caretaker(); $caretaker->addMemento($originator->saveStateToMemento()); // change state $originator->setState("State2"); // restore state from Memento $originator->getStateFromMemento($caretaker->getMemento(0)); // output state echo $originator->getState(); // outputs "State1" |
In this example, the Memento pattern is used to save and restore the state of the Originator object without violating its encapsulation. The Caretaker object stores the Memento objects and retrieves them when needed to restore the state of the Originator object.