-
Notifications
You must be signed in to change notification settings - Fork 2
/
Memento.php
91 lines (76 loc) · 1.98 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace DesignPatterns\Behavioral;
/**
* Editor which have possibility to save and restore the state if necessary.
*/
class Editor
{
// content is hidden
private $content = '';
public function type(string $words)
{
$this->content = $this->content . ' ' . $words;
}
public function getContent(): string
{
return $this->content;
}
/**
* Saves the current state inside a memento snapshot
*/
public function save(): EditorMemento
{
return new EditorMemento($this->content);
}
/**
* Restores the editor's state from a memento object
* @param EditorMemento $memento
*/
public function restore(EditorMemento $memento)
{
$this->content = $memento->getContent();
}
}
/**
* The Memento interface provides a way to retrieve the memento's metadata, such as creation date
*/
interface Memento
{
public function getDate();
}
/**
* Concrete Memento contains the infrastructure for storing the editor's state.
* Tip: in real life you probably prefer to make a copy of an object's state easier
* by simply using a PHP serialization.
*/
class EditorMemento implements Memento
{
protected $content;
protected $date;
public function __construct(string $content)
{
$this->content = $content;
$this->date = date('Y-m-d');
}
public function getContent()
{
return $this->content;
}
public function getDate()
{
return $this->date;
}
}
# Client code example
$editor = new Editor();
$editor->type('This is the first sentence.');
$editor->type('This is second.');
// make a snapshot
$memento = $editor->save();
$editor->type('And this is third.');
echo $editor->getContent() . PHP_EOL;
/* Output: This is the first sentence. This is second. And this is third. */
// restore the state from snapshot
$editor->restore($memento);
echo $editor->getContent() . PHP_EOL;
/* Output: This is the first sentence. This is second. */