Created
March 17, 2015 22:30
-
-
Save unnikked/fe48953e1605a3ab78b9 to your computer and use it in GitHub Desktop.
PHP Closure Event Dispatcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Event { | |
private $events = []; | |
public function on($event, $callback, $priority = 0) { | |
// check if an event is not already created | |
if (!isset($this->events[$event])) $this->events[$event] = new \SplPriorityQueue(); | |
// make $this available in closures | |
if (is_object($callback) && $callback instanceof \Closure) { | |
$callback = $callback->bindTo($this, $this); | |
} | |
// add the event to the priority queue | |
$this->events[$event]->insert($callback, $priority); | |
} | |
public function trigger($event, $params=[]){ | |
if (!isset($this->events[$event])){ | |
return $this; | |
} | |
$queue = $this->events[$event]; | |
$queue->top(); | |
// process the queue | |
while($queue->valid()){ | |
$action = $queue->current(); | |
if (is_callable($action)){ | |
if (call_user_func_array($action, $params) === false) { | |
break; // stop propagation on error | |
} | |
} | |
$queue->next(); | |
} | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment