-
-
Save r37r0m0d3l/5734638 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* 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