-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObservable.php
94 lines (78 loc) · 2.25 KB
/
Observable.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
<?php
/*
* Observable object that can be extended to objects that need to be observed.
* It is coupled with the Observers class.
*/
namespace FormHelper;
class Observable {
protected $observers = array();
protected $changed = false;
public function __construct(){
}
/**
* Adds an Observer to this Observable
* @param Observer $observer
*/
public function addObserver(Observer $observer) {
$this->observers[] = $observer;
}
/**
* Removes an Observer from this Observable if present
* @param Observer $observer
* @return boolean
*/
public function removeObserver(Observer $observer) {
foreach($this->observers as $key => $obs) {
if($observer == $obs) {
array_slice($this->observers, $key, 1);
return true;
}
}
return false;
}
/**
* Set observers attribute to an empty array
*/
public function removeObservers() {
$this->observers = array();
}
/**
* Return the number of observers
*/
public function countObservers() {
return count($this->observers);
}
/**
* Return True if this Observable is changed, False otherwise
* @return type Boolean
*/
public function hasChanged(){
return $this->changed;
}
/**
* Set this Observable as changed
*/
public function setChanged($arg=null){
$this->changed = true;
$this->notifyObservers($arg);
}
/**
* Sets the state of this Observable to unChanged if all Observers have
* been notified of the most recent change.
*/
public function clearChanged() {
$this->changed = false;
}
/**
* Invokes the update() method on all Observers on this Observable
* @param type $arg
*/
public function notifyObservers($arg=null) {
foreach($this->observers as $observer) {
$observer->update($this, $arg);
}
//all observers have been notified, the state can return to unchanged
$this->clearChanged();
}
}
?>