forked from DesignPatternsPHP/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathObserver.php
94 lines (82 loc) · 2.03 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
<?php
namespace DesignPatterns;
/**
* Observer pattern
*
* Purpose:
* to implement a publish/subscribe behaviour to an object, whenever a "Subject" object changes it's state, the attached
* "Observers" will be notified. It is used to shorten the amount of coupled objects and uses loose coupling instead
*
* Examples:
* - a message queue system is observed to show the progress of a job in a GUI
*
* PHP already defines two interfaces that can help to implement this pattern: SplObserver and SplSubject
*
*/
class UserObserver implements \SplObserver
{
public function update(\SplSubject $subject)
{
echo get_class($subject) . ' has been updated';
}
}
class User implements \SplSubject
{
protected $_data = array();
/**
* @var array
*/
protected $_observers = array();
/**
* attach a new observer
*
* @param \SplObserver $observer
* @return void
*/
public function attach(\SplObserver $observer)
{
$this->_observers[] = $observer;
}
/**
* detach an observer
*
* @param \SplObserver $observer
* @return void
*/
public function detach(\SplObserver $observer)
{
$index = array_search($observer, $this->_observers);
if (false !== $index) {
unset($this->_observers[$index]);
}
}
/**
*
*
* @return void
*/
public function notify()
{
/** @var SplObserver $observer */
foreach ($this->_observers as $observer) {
$observer->update($this);
}
}
/**
* Ideally one would better write setter/getter for all valid attributes and only call notify()
* on attributes that matter when changed
*
* @param $name
* @param $value
* @return void
*/
public function __set($name, $value)
{
$this->_data[$name] = $value;
// notify the observers, that user has been updated
$this->notify();
}
}
$user = new User();
$user->attach(new UserObserver());
$user->notify();