Skip to content

Instantly share code, notes, and snippets.

@unnikked
Created March 17, 2015 22:30
Show Gist options
  • Save unnikked/fe48953e1605a3ab78b9 to your computer and use it in GitHub Desktop.
Save unnikked/fe48953e1605a3ab78b9 to your computer and use it in GitHub Desktop.
PHP Closure Event Dispatcher
<?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