How to use the Memento design pattern in PHP for restoring state?

Member

by ryleigh , in category: PHP General , 2 years ago

How to use the Memento design pattern in PHP for restoring state?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 2 years ago

@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. Create a Memento class that contains the state of the object to be saved and restored. The Memento class should have methods for getting and setting the state.
 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. Create an Originator class that contains the object whose state needs to be saved and restored. The Originator class should have methods for saving and restoring its state using a Memento object.
 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. Create a Caretaker class that is responsible for storing and retrieving Memento objects. The Caretaker class should have methods for adding and getting Memento objects from a list.
 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. Test the Memento pattern by creating an Originator object, setting its state, saving its state to a Memento object, changing its state, and then restoring its original state using the Memento object.
 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.