-
Notifications
You must be signed in to change notification settings - Fork 4
/
observer.php
76 lines (64 loc) · 1.64 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
<?php
/**
* Observer pattern example
*
* @author Christian Bergau <[email protected]>
* @copyright Free for all
* @link http://en.wikipedia.org/wiki/Observer_pattern
*/
/*
These interfaces are part of the Standard PHP library and can be used > 5.1.0
http://www.php.net/manual/en/class.splsubject.php
http://www.php.net/manual/en/class.splobserver.php
interface SplObserver {
abstract public function update ($subject) {}
}
interface SplSubject {
abstract public function attach ($observer) {}
abstract public function detach ($observer) {}
abstract public function notify () {}
}
*/
class Subject implements SplSubject
{
protected $observers = array();
protected $value = 0;
public function attach(SplObserver $observer)
{
$this->observers[] = $observer;
}
public function detach(SplObserver $observer)
{
$this->observers = array_diff($this->observers, array($observer));
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function increaseValue($increaseBy)
{
$this->value += $increaseBy;
$this->notify();
}
public function getValue()
{
return $this->value;
}
}
class ValueObserver implements SplObserver
{
public function update(SplSubject $subject)
{
if ($subject->getValue() > 20) {
echo "Value is greater than 20!";
}
}
}
$subject = new Subject();
$subject->attach(new ValueObserver());
$subject->increaseValue(10);
$subject->increaseValue(4);
$subject->increaseValue(3);
$subject->increaseValue(7);