-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_one.php
106 lines (92 loc) · 2.21 KB
/
example_one.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
<?php
####################################
##### OBSERVER DESIGN PATTERN #####
####################################
class Model implements SplSubject
{
protected $observers;
/**
* Store observers in SplObjectStorage
*/
public function __construct()
{
$this->observers = new SplObjectStorage();
}
/**
* Attach observer
* @param SplObserver $observer
* @return void
*/
public function attach(SplObserver $observer)
{
$this->observers->attach($observer);
}
/**
* Detach observer
* @param SplObserver $observer
* @return void
*/
public function detach(SplObserver $observer)
{
$this->observers->detach($observer);
}
/**
* When model subject is updated notify the observer
* @return void
*/
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
/**
* This method set any anonymous property
* @param $name
* @param $value
* @return void
*/
public function __set($name, $value)
{
$this->data[$name] = $value;
$this->notify();
}
}
class ModelObserver implements SplObserver
{
/**
* Notify when subject is updated
* @param SplSubject $subject
* @return void
*/
public function update(SplSubject $subject)
{
echo get_class($subject) . ' has been updated' . '<br>';
}
}
class Observer2 implements SplObserver
{
/**
* Notify when subject is udpated
* @param SplSubject $subject
* @return void
*/
public function update(SplSubject $subject)
{
echo get_class($subject) . ' has been updated' . '<br>';
}
}
// Instantiate the model class for 2 different objects
$model1 = new Model();
$model2 = new Model();
// Instantiate the observers
$modelObserver = new ModelObserver();
$observer2 = new Observer2();
// Attach the observers to $model1
$model1->attach($modelObserver);
$model2->attach($observer2);
// Attach the observers to $model2
$model2->attach($observer2);
// Change the subject properties
$model1->title = 'Ba Ba Black Ship..';
$model2->body = 'Twinkle Twinkle Little Star..';