Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sovetski/b0dfdee9f93acc44a0beebc43e114696 to your computer and use it in GitHub Desktop.
Save sovetski/b0dfdee9f93acc44a0beebc43e114696 to your computer and use it in GitHub Desktop.
PHP event listener simple example
<?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']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment