Skip to content

Instantly share code, notes, and snippets.

@lastguest
Created February 8, 2013 16:56
Show Gist options
  • Save lastguest/4740342 to your computer and use it in GitHub Desktop.
Save lastguest/4740342 to your computer and use it in GitHub Desktop.
PHP: Events - A module class for handling events
<?php
/**
* Event class
* A module class for handling events
*
* @author Stefano Azzolini <lastguest@gmail.com>
*/
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