Skip to content

Instantly share code, notes, and snippets.

@nicolasegp
Last active May 28, 2023 22:06
Show Gist options
  • Save nicolasegp/0c6707774b5d8bb8a0edb7426d512d3d to your computer and use it in GitHub Desktop.
Save nicolasegp/0c6707774b5d8bb8a0edb7426d512d3d to your computer and use it in GitHub Desktop.
[PHP] Eventos y Disparadores
<?php
/**
*
* Eventos y Disparadores
* @author Nicolás Giacaman <nicolas.egp@gmail.com>
* @url http://nicolasg.cf
* @fork https://gist.github.com/im4aLL/548c11c56dbc7267a2fe96bda6ed348b
*
*/
class Event {
protected static $_X = [];
public static function Create($ID = '', $Func = '') {
try {
if(empty($ID) OR empty($Func))
throw new Exception("ID o Func Vacios!!");
if(isset(self::$_X[$ID]))
throw new Exception("{$ID} :: Ya existe.");
self::$_X[$ID] = $Func;
}
catch (Exception $_E) {
echo '<b>[Event::Create]</b> '.$_E->getMessage();
}
}
public static function Trigger($ID = '') {
try {
if(empty($ID))
throw new Exception("ID Vacio!!");
@$Func = self::$_X[$ID];
if(isset($Func)) {
if(is_callable($Func)) {
$Args = func_get_args();
array_shift($Args);
if(call_user_func_array($Func, $Args) === FALSE)
throw new Exception("{$ID} :: Error Callback.");
}
}
}
catch (Exception $_E) {
echo '<b>[Event::Trigger]</b> '.$_E->getMessage();
}
}
}
// -- DEMO --
Event::Create('demo1', function($X, $Y) {
echo $X + $Y;
});
Event::Create('demo2', function($X, $Y) {
echo $X * $Y;
});
// -----
Event::Trigger('demo2', 2, 5);
Event::Trigger('demo3', 2, 5);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment