forked from cbergau/PHPDesignPatterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemento.php
64 lines (54 loc) · 1.33 KB
/
memento.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
/**
* Memento pattern example
*
* @author Christian Bergau <[email protected]>
* @copyright Free for all
* @link http://en.wikipedia.org/wiki/Memento_pattern
*/
class Originator
{
protected $state = '';
public function setState($state)
{
echo 'Originator: Setting state to: ' . $state . PHP_EOL;
$this->state = $state;
}
public function saveToMemento()
{
return new Memento($this->state);
}
public function restoreFromMemento(Memento $memento)
{
$this->state = $memento->getSavedState();
echo "Originator: State after restoring from Memento: " . $this->state . PHP_EOL;
}
}
class Memento
{
protected $state;
public function __construct($state)
{
$this->state = $state;
}
public function getSavedState()
{
return $this->state;
}
}
class Caretaker
{
public function doIt()
{
$savedStates = array();
$originator = new Originator();
$originator->setState('StateOne');
$savedStates[] = $originator->saveToMemento();
$originator->setState('StateTwo');
$savedStates[] = $originator->saveToMemento();
$originator->setState('StateThree');
$originator->restoreFromMemento($savedStates[1]);
}
}
$careTaker = new Caretaker();
$careTaker->doIt();