-
-
Save im4aLL/548c11c56dbc7267a2fe96bda6ed348b to your computer and use it in GitHub Desktop.
<?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']); | |
} |
Cool! Thanks a lot!
@shadowng Thanks buddy! @AntoninaSych thanks!
good
good example
very useful example
@nicolasegp because of the username change, link is changing too:
https://gist.github.com/nicolasegp/0c6707774b5d8bb8a0edb7426d512d3d
@Synida thx I already edited the link 👍
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]);
Great code!
👍
I made some changes to your code and added the support to parameters.
If you are interested:
https://gist.github.com/nicolasegp/0c6707774b5d8bb8a0edb7426d512d3d