Last active
September 6, 2023 23:24
-
-
Save lastguest/7709512 to your computer and use it in GitHub Desktop.
PHP global event handling in a single function.
This file contains hidden or 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 | |
/* | |
* 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); | |
} | |
} |
This file contains hidden or 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 | |
// 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