-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.php
63 lines (50 loc) · 1.08 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
<?php
/**
* Interface Observer / Listener
*/
interface Observer
{
public function update(): void;
}
class ObserverImplementationA implements Observer
{
public function update(): void
{
echo '=^-^=' . '<br>';
}
}
class ObserverImplementationB implements Observer
{
public function update(): void
{
echo '>^_^<' . '<br>';
}
}
class Subject
{
private array $observers = [];
public function registerObserver(Observer $observer): void
{
$this->observers[] = $observer;
}
public function execute(): string
{
$this->notifyObserver();
return __METHOD__;
}
private function notifyObserver(): void
{
foreach ($this->observers as $observer) {
$observer->update();
}
}
}
/**
* Client
*/
$subject = new Subject();
$observerImplementationA = new ObserverImplementationA();
$observerImplementationB = new ObserverImplementationB();
$subject->registerObserver($observerImplementationA);
$subject->registerObserver($observerImplementationB);
echo $subject->execute();