-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathobserver-subject-events.php
408 lines (362 loc) · 8.83 KB
/
observer-subject-events.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
<?php
/**
* The EventDispatcher class provides a container for storing and dispatching
* events. Modifications have been added to trigger specific methods (events)
* by name as opposed to forcing the usage of update(). The singleton pattern
* was also removed in addition to adding methods to override the default usage
* of __call().
*
* Based on the original code:
* http://forrst.com/posts/PHP_Event_handling-5Ke
*
* Ideas for scaling in the cloud:
* http://www.slideshare.net/beberlei/towards-the-cloud-eventdriven-architectures-in-php
*
* @author Thomas RAMBAUD
* @author Corey Ballou
* @version 1.1
* @access public
*/
class EventDispatcher {
// stores all created events
private $_events = array();
/**
* Default constructor.
*
* @access public
* @return void
*/
public function __construct() {
// do nothing
}
/**
* Determine the total number of events.
*
* @access public
* @return int
*/
public function count()
{
return count($this->_events);
}
/**
* Add a new event by name.
*
* @access public
* @param string $name
* @param mixed $triggersMethod
* @return Event
*/
public function add($name, $triggersMethod = NULL)
{
if (!isset($this->_events[$name])) {
$this->_events[$name] = new Event($triggersMethod);
}
return $this->_events[$name];
}
/**
* Retrieve an event by name. If one does not exist, it will be created
* on the fly.
*
* @access public
* @param string $name
* @return Event
*/
public function get($name)
{
if (!isset($this->_events[$name])) {
return $this->add($name);
}
return $this->_events[$name];
}
/**
* Retrieves all events.
*
* @access public
* @return array
*/
public function getAll()
{
return $this->_events;
}
/**
* Trigger an event. Returns the event for monitoring status.
*
* @access public
* @param string $name
* @param mixed $data The data to pass to the triggered event(s)
* @return void
*/
public function trigger($name, $data)
{
$this->get($name)->notify($data);
}
/**
* Remove an event by name.
*
* @access public
* @param string $name
* @return bool
*/
public function remove($name)
{
if (isset($this->_events[$name])) {
unset($this->_events[$name]);
return true;
}
return false;
}
/**
* Retrieve the names of all current events.
*
* @access public
* @return array
*/
public function getNames()
{
return array_keys($this->_events);
}
/**
* Magic __get method for the lazy who don't wish to use the
* add() or get() methods. It will add an event if it doesn't exist,
* or simply return an existing event.
*
* @access public
* @return Event
*/
public function __get($name)
{
return $this->add($name);
}
}
/**
* Attach event handlers to an event to be notified
* @author Thomas RAMBAUD
* @version 1.0
* @access public
*/
class Event implements SplSubject {
// stores all attached observers
private $_observers;
/**
* Default constructor to initialize the observers.
*
* @access public
* @return void
*/
public function __construct()
{
$this->_observers = new SplObjectStorage();
}
/**
* Wrapper for the attach method, allowing for the addition
* of a method name to call within the observer.
*
* @access public
* @param SplObserver $event
* @param mixed $triggersMethod
* @return Event
*/
public function bind(SplObserver $event, $triggersMethod = NULL)
{
$this->_observers->attach($event, $triggersMethod);
return $this;
}
/**
* Attach a new observer for the particular event.
*
* @access public
* @param SplObserver $event
* @return Event
*/
public function attach(SplObserver $event)
{
$this->_observers->attach($event);
return $this;
}
/**
* Detach an existing observer from the particular event.
*
* @access public
* @param SplObserver $event
* @return Event
*/
public function detach(SplObserver $event)
{
$this->_observers->detach($event);
return $this;
}
/**
* Notify all event observers that the event was triggered.
*
* @access public
* @param mixed &$args
*/
public function notify(&$args = null)
{
$this->_observers->rewind();
while ($this->_observers->valid()) {
$triggersMethod = $this->_observers->getInfo();
$observer = $this->_observers->current();
$observer->update($this, $triggersMethod, $args);
// on to the next observer for notification
$this->_observers->next();
}
}
/**
* Retrieves all observers.
*
* @access public
* @return SplObjectStorage
*/
public function getHandlers()
{
return $this->_observers;
}
}
/**
* You can attach an EventListener to an event to be notified when a specific
* event has occured. Although unused, you can use
*
* @author Thomas RAMBAUD
* @version 1.0
* @access public
*/
abstract class EventListener implements SplObserver {
// holds all states
private $_states = array();
/**
* Returns all states.
*
* @access public
* @return void
*/
public function getStates()
{
return $this->_states;
}
/**
* Adds a new state.
*
* @access public
* @param mixed $state
* @param int $stateValue
* @return void
*/
public function addState($state, $stateValue = 1)
{
$this->_states[$state] = $stateValue;
}
/**
* @Removes a state.
*
* @access public
* @param mixed $state
* @return bool
*/
public function removeState($state)
{
if ($this->hasState($state)){
unset($this->_states[$state]);
return TRUE;
}
return FALSE;
}
/**
* Checks if a given state exists.
*
* @access public
* @param mixed $state
* @return bool
*/
public function hasState($state)
{
return isset($this->_states[$state]);
}
/**
* Implementation of SplObserver::update().
*
* @access public
* @param SplSubject $subject
* @param mixed $triggersMethod
* @param mixed &$arg Any passed in arguments
*/
public function update(SplSubject $subject, $triggersMethod = NULL, &$arg = NULL) {
if ($triggersMethod) {
if (method_exists($this, $triggersMethod)) {
$this->{$triggersMethod}($arg);
} else {
throw new Exception('The specified event method ' . get_called_class() . '::' . $triggersMethod . ' does not exist.');
}
} else {
throw new Exception('The specified event method ' . get_called_class() . '::' . 'update() does not exist.');
}
}
}
/**
* An example of creating an email notification event that gets triggered
* when a new comment is added.
*/
class EmailNotification extends EventListener {
public function notify(&$comment)
{
$recipients = array('[email protected]', '[email protected]');
foreach ($recipients as $email) {
echo 'Notifying recipient ' . $email . PHP_EOL;
echo 'Comment: ' . print_r($comment, true) . PHP_EOL;
//mail($email, 'Comment added', $comment['body']);
}
}
}
/**
* An example of creating a new comment logger that gets triggered when a
* new comment is added.
*/
class CommentLogger extends EventListener {
public function comment(&$comment)
{
echo 'Logging the comment:' . PHP_EOL;
echo print_r($comment, true) . PHP_EOL;
//error_log('notice', $comment)
}
}
//===================================================
// EXAMPLE USAGE OF THE ABOVE CLASSES BELOW THIS LINE
//===================================================
/**
* Quick example function of adding a comment.
*/
function add_comment($comment_info, EventDispatcher $EventDispatcher)
{
// insert the comment into the database
$sql = sprintf('INSERT INTO comments SET created_by = %d, comment = %s, created_ts = %s',
$comment_info['created_by'],
'"' . mysql_real_escape_string($comment_info['comment']) . '"',
'"' . time() . '"');
// myqsl_query($sql);
// notify any event listeners of onCommentAdded
$EventDispatcher->onCommentAdded->notify($comment_info);
}
// load up an instance of the event handler
$EventDispatcher = new EventDispatcher();
// watch for comment being added and attach notification and logging
$EventDispatcher->onCommentAdded->bind(new EmailNotification(), 'notify');
$EventDispatcher->onCommentAdded->bind(new CommentLogger(), 'comment');
// trigger the bound events for add_comment
add_comment(
array(
'created_by' => 1,
'comment' => 'Lorem ipsum dolor sir amet.'
),
$EventDispatcher
);
/*
You can perform the same thing above by doing the following:
// add a new event
$Events->add('onCommentAdded');
// bind some event handlers to the event
$Events->get('onCommentAdded')->attach(new EmailNotification());
$Events->get('onCommentAdded')->attach(new CommentLogger());
This avoids using the magic method __get(), which is particularly slow.
It really depends on if you want to decrease readability.
*/