Skip to content

Instantly share code, notes, and snippets.

@lastguest
Last active September 6, 2023 23:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lastguest/7709512 to your computer and use it in GitHub Desktop.
Save lastguest/7709512 to your computer and use it in GitHub Desktop.
PHP global event handling in a single function.
<?php
/*
* Use
* event('eventname',function(){ ... })
* to add an event handler for 'eventname' event.
*
* Trigger an event with
* event('eventname')
*
* You can also pass parameters to handlers triggering the event
* passing an array as the second parameter:
* event('eventname',[1,2,3])
*
*/
function event($name,$cb = null){
static $e = array();
if ( is_callable($cb) ){
empty( $e[$name] ) ? $e[$name] = array($cb) : $e[$name][] = $cb;
} elseif ( false === empty($e[$name]) ) {
$a = is_array($cb) ? $cb : array();
foreach ($e[$name] as $eh) call_user_func_array($eh,$a);
}
}
<?php
// Example :
// http://3v4l.org/tS5Sd
// Add a foo event handler
event('foo',function(){
print_r(func_get_args());
});
// Add another foo event handler
event('foo',function(){
echo 'Hello, friend!';
});
// Call foo event with parameters
event('foo',[1,2]);
// Call bar event (does nothing)
event('bar');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment