-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathObserver.php
116 lines (101 loc) · 2.46 KB
/
Observer.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
namespace DesignPatterns\Behavioral;
use SplObserver;
use SplSubject;
/**
* PHP has several built-in interfaces \SplSubject, \SplObserver which help us
* to build implementations of the Observer.
* Trait encapsulates an implementation of basic \SplSubject methods
*/
trait Observable
{
/**
* List of observers
* Tip: you also can use \SplObjectStorage instead of simple array
* @var SplObserver[]
*/
private $observers = [];
/**
* Attach an observer
* @param SplObserver $observer
*/
public function attach(SplObserver $observer)
{
$this->observers[] = $observer;
}
/**
* Detach an observer
* @param SplObserver $observer
*/
public function detach(SplObserver $observer)
{
foreach ($this->observers as $key => $obs) {
if ($obs === $observer) {
unset($this->observers[$key]);
}
}
}
/**
* Notify an observer
*/
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
}
/**
* Shopping cart owns some important state and notifies observers when the state changes.
*/
class Cart implements SplSubject
{
use Observable;
/**
* Some business logic state
* @var int
*/
protected $balance = 0;
// Business logic
/**
* Changes state and notifies all subscribers about it
* @param int $balance
*/
public function setBalance(int $balance)
{
if ($this->balance !== $balance) {
$this->balance = $balance;
$this->notify();
}
}
/**
* Return current state
*/
public function getBalance()
{
return $this->balance;
}
}
/**
* Concrete observers react to the updates generated by the subject they had been attached to
*/
class LoggingListener implements SplObserver
{
/**
* Receive update from subject
* @param SplSubject $subject
*/
public function update(SplSubject $subject)
{
if (!$subject instanceof Cart) {
return;
}
echo 'Notification: balance of the shopping cart was changed to ' . $subject->getBalance() . PHP_EOL;
}
}
# Client code example
$cart = new Cart(); // subject
$cart->attach(new LoggingListener()); // attach an Observer
$cart->setBalance(10); // trigger an event
/* Output:
Notification: balance of the shopping cart was changed to 10 */