事件管理一直是js之类的语言的法宝,事件注册和调用过程中能减少代码的复杂程度,evenement是基于php5.4特性写的一个时间管理程序。
namespace Evenement;
trait EventEmitterTrait
{
protected $listeners = [];
public function on($event, callable $listener)
{
if (!isset($this->listeners[$event])) {
$this->listeners[$event] = [];
}
$this->listeners[$event][] = $listener;
}
public function once($event, callable $listener)
{
$onceListener = function () use (&$onceListener, $event, $listener) {
$this->removeListener($event, $onceListener);
call_user_func_array($listener, func_get_args());
};
$this->on($event, $onceListener);
}
public function removeListener($event, callable $listener)
{
if (isset($this->listeners[$event])) {
$index = array_search($listener, $this->listeners[$event], true);
if (false !== $index) {
unset($this->listeners[$event][$index]);
}
}
}
public function removeAllListeners($event = null)
{
if ($event !== null) {
unset($this->listeners[$event]);
} else {
$this->listeners = [];
}
}
public function listeners($event)
{
return isset($this->listeners[$event]) ? $this->listeners[$event] : [];
}
public function emit($event, array $arguments = [])
{
foreach ($this->listeners($event) as $listener) {
call_user_func_array($listener, $arguments);
}
}
}
composer安装
{ "require": { "evenement/evenement": "2.0.*" } }一个调用实例
require 'vendor/autoload.php';
$emitter = new Evenement\EventEmitter();
$emitter->on('user.created', function (User $user) use ($logger) {
$logger->log(sprintf("User '%s' was created.", $user->getLogin()));
});
$emitter->emit('user.created', array($user));