-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver_patern.php
More file actions
83 lines (65 loc) · 1.79 KB
/
observer_patern.php
File metadata and controls
83 lines (65 loc) · 1.79 KB
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
<?php
class Subject implements \SplSubject{
public $state;
private $observers;
public function __construct(){
$this->observers = new \SplObjectStorage();
}
public function attach(\SplObserver $observer)
: void{
echo "Subject: Attached an observer.\n";
$this->observers->attach($observer);
}
public function detach(\SplObserver $observer)
: void{
$this->observers->detach($observer);
echo "Subject: Detached an observer.\n";
}
public function notify()
: void{
echo "Subject: Notifying observers...\n";
foreach($this->observers as $observer){
$observer->update($this);
}
}
public function someBusinessLogic()
: void{
echo "\nSubject: I'm doing something important.\n";
$this->state = rand(0, 100);
echo "Subject: My state has just changed to: {$this->state}\n";
$this->notify();
}
}
class ConcreteObserverA implements \SplObserver{
public function update(\SplSubject $subject)
: void{
if($subject->state < 3){
echo "ConcreteObserverA: Reacted to the event.\n";
}
}
}
class ConcreteObserverB implements \SplObserver{
public function update(\SplSubject $subject)
: void{
if($subject->state == 0 || $subject->state >= 2){
echo "ConcreteObserverB: Reacted to the event.\n";
}
}
}
/**
* The client code.
*/
$subject = new Subject();
$o1 = new ConcreteObserverA();
$subject->attach($o1);
$o2 = new ConcreteObserverB();
$subject->attach($o2);
//$subject->someBusinessLogic();
//$subject->someBusinessLogic();
//
//$subject->detach($o2);
////$subject->detach($o1);
//
$subject->someBusinessLogic();
echo "notity\n";
$subject->notify();