Last active
August 18, 2024 18:18
-
-
Save im4aLL/548c11c56dbc7267a2fe96bda6ed348b to your computer and use it in GitHub Desktop.
PHP event listener simple example
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 | |
// Used in https://github.com/im4aLL/roolith-event | |
class Event { | |
private static $events = []; | |
public static function listen($name, $callback) { | |
self::$events[$name][] = $callback; | |
} | |
public static function trigger($name, $argument = null) { | |
foreach (self::$events[$name] as $event => $callback) { | |
if($argument && is_array($argument)) { | |
call_user_func_array($callback, $argument); | |
} | |
elseif ($argument && !is_array($argument)) { | |
call_user_func($callback, $argument); | |
} | |
else { | |
call_user_func($callback); | |
} | |
} | |
} | |
} | |
class User { | |
public function login() { | |
return true; | |
} | |
public function logout() { | |
return true; | |
} | |
public function updated() { | |
return true; | |
} | |
} | |
// Usage | |
// ================================== | |
Event::listen('login', function(){ | |
echo 'Event user login fired! <br>'; | |
}); | |
$user = new User(); | |
if($user->login()) { | |
Event::trigger('login'); | |
} | |
// Usage with param | |
// ================================== | |
Event::listen('logout', function($param){ | |
echo 'Event '. $param .' logout fired! <br>'; | |
}); | |
if($user->logout()) { | |
Event::trigger('logout', 'user'); | |
} | |
// Usage with param as array | |
// ================================== | |
Event::listen('updated', function($param1, $param2){ | |
echo 'Event ('. $param1 .', '. $param2 .') updated fired! <br>'; | |
}); | |
if($user->updated()) { | |
Event::trigger('updated', ['param1', 'param2']); | |
} |
Working on parsing my files to document events. Regex below, taking suggestions on anything missing or alternative regexes thanks.
preg_match('/Event::trigger\(((\'|\").*)(,|\',) \[(.*)]\)/', $line, $matches);
Package published https://github.com/im4aLL/roolith-event if anyone wants to use it.
it doesn't want to pass an array to parameters , why ?
@fdciabdul which parameter you are talking about?
@fdciabdul which parameter you are talking about?
i mean like this
Event::listen('logout', function($param){
echo 'Event '. $param .' logout fired! <br>';
});
if($user->logout()) {
$data = array("first","second","third");
Event::trigger('logout', $data);
}
the output is just first
, not return the array itself
@fdciabdul you can call multiple params function($param1, $param2, $param3)
or if you want the whole array then just call it like this -
Event::trigger('logout', [$data]);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Synida thx I already edited the link 👍