-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_two.php
131 lines (113 loc) · 2.71 KB
/
example_two.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?php
####################################
##### OBSERVER DESIGN PATTERN #####
####################################
abstract class AbstractSubject
{
/**
* Attach observer
* @param AbstractObserver $observer_in
* @return mixed
*/
abstract function attach(AbstractObserver $observer_in);
/**
* Detach observer
* @param AbstractObserver $observer_in
* @return mixed
*/
abstract function detach(AbstractObserver $observer_in);
/**
* Notify observer
* @return mixed
*/
abstract function notify();
}
abstract class AbstractObserver
{
/**
* Subject updated
* @param AbstractSubject $subject_in
* @return mixed
*/
abstract function update(AbstractSubject $subject_in);
}
class Subject extends AbstractSubject
{
private $observers = array();
function __construct(){}
/**
* Attach observer
* @param AbstractObserver $observer_in
* @return mixed|void
*/
function attach(AbstractObserver $observer_in)
{
//could also use array_push($this->observers, $observer_in);
$this->observers[] = $observer_in;
}
/**
* Detach observer
* @param AbstractObserver $observer_in
* @return mixed|void
*/
function detach(AbstractObserver $observer_in)
{
//$key = array_search($observer_in, $this->observers);
foreach ($this->observers as $okey => $oval) {
if ($oval == $observer_in) {
unset($this->observers[$okey]);
}
}
}
/**
* Notify observer
* @return mixed|void
*/
function notify()
{
foreach ($this->observers as $obs) {
$obs->update($this);
}
}
/**
* Update subject property and notify observer
* @param $newFavorites
* @return void
*/
function updateFavorites($newFavorites)
{
$this->favorites = $newFavorites;
$this->notify();
}
/**
* Get updated info
* @return mixed
*/
function getFavorites()
{
return $this->favorites;
}
}
class Observer extends AbstractObserver
{
/**
* Notify when subject is updated
* @param AbstractSubject $subject
* @return mixed|void
*/
public function update(AbstractSubject $subject)
{
echo get_class($subject) . ' has been updated' . '<br>';
}
}
// Instantiate the subject
$subject = new Subject();
// Instantiate the observers
$observer = new Observer();
// Attach the observers to subject
$subject->attach($observer);
$subject->updateFavorites('Hello Subject Updated');
$subject->updateFavorites('Hello Subject Again Updated');
// Detach the observer
$subject->detach($observer);
?>