forked from DesignPatternsPHP/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Caretaker.php
49 lines (40 loc) · 1.21 KB
/
Caretaker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
namespace DesignPatterns\Behavioral\Memento;
class Caretaker
{
protected $history = array();
/**
* @return Memento
*/
public function getFromHistory($id)
{
return $this->history[$id];
}
/**
* @param Memento $state
*/
public function saveToHistory(Memento $state)
{
$this->history[] = $state;
}
public function runCustomLogic()
{
$originator = new Originator();
//Setting state to State1
$originator->setState("State1");
//Setting state to State2
$originator->setState("State2");
//Saving State2 to Memento
$this->saveToHistory($originator->getStateAsMemento());
//Setting state to State3
$originator->setState("State3");
// We can request multiple mementos, and choose which one to roll back to.
// Saving State3 to Memento
$this->saveToHistory($originator->getStateAsMemento());
//Setting state to State4
$originator->setState("State4");
$originator->restoreFromMemento($this->getFromHistory(1));
//State after restoring from Memento: State3
return $originator->getStateAsMemento()->getState();
}
}