Skip to content

Instantly share code, notes, and snippets.

@r37r0m0d3l
Forked from lastguest/Events.class.php
Created June 8, 2013 09:20
Show Gist options
  • Save r37r0m0d3l/5734638 to your computer and use it in GitHub Desktop.
Save r37r0m0d3l/5734638 to your computer and use it in GitHub Desktop.
<?php
/**
* Event class
* A module class for handling events
*
* @author Stefano Azzolini <[email protected]>
*/
class Events {
/**
* The Events <-> Handlers internal register
* @static
* @var array
*/
static private $register = array();
/**
* Register and event handler
*
* @static
* @param string $event The event descriptor
* @param callback $callback The callback for the defined handler
* @example
* // Register custom handler for "test.event"
* Events::on('test.event',function($a=1,$b=2){
* echo "Called TEST with (".$a.",".$b.")!\n";
* });
*/
static public function on($event,$callback){
static::$register[$event][] = $callback;
}
/**
* Remove all handlers for an event
*
* @static
* @param string $event The event descriptor
* @example
* Events::off('data.received');
*/
static public function off($event){
unset (static::$register[$event]);
}
/**
* Trigger all registered event handlers for a specified event
*
* @static
* @return array The handler results queue
* @example
* Events::trigger('test.event',12,'foobar');
*/
static public function trigger(){
$args = func_get_args();
$event = array_shift($args);
// No handlers founded
if(static::$register[$event] == false) return null;
$results = array();
// Trigger all handler for the event
foreach(static::$register[$event] as $handler){
$results[] = call_user_func_array($handler,$args);
}
// Get the result queue
return $results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment