当前位置: 首页 > 文档资料 > Group-Co 开发文档 >

基础服务 - EventDispatcher事件调度

优质
小牛编辑
131浏览
2023-12-01

EventDispatcher事件调度

派发事件 {#2自定义事件}

EventDispatcher::dispatch($eventName, Event $event = null)
  1. use EventDispatcher;
  2. EventDispatcher::dispatch('user.login');
  3. //你也可以在抛出事件时,塞入事件对象
  4. EventDispatcher::dispatch('user.register', new \Event($user));
  5. EventDispatcher::dispatch('user.register', new \UserEvent($user));

绑定监听事件

EventDispatcher::addListener($eventName, $listener, $priority = 0)

* @param eventName

  1. \* @param listener 可以是一个callback方法或者一个继承于Listner的对象实例
  2. \* @param priority 越大越早执行
EventDispatcher::removeListener($eventName, $listener)

* @param eventName

  1. \* @param listener 可以是一个callback方法或者一个继承于Listner的对象实例
EventDispatcher::hasListeners($eventName = null)
EventDispatcher::getListeners($eventName = null)
例子:
  1. use EventDispatcher;
  2. $listener = new KernalResponseListener();
  3. //定义一个事件名称,触发的监听器,和一个重要指数
  4. EventDispatcher::addListener('kernal.responese', $listener, 10);
  5. EventDispatcher::removeListener('kernal.responese', $listener);
  6. EventDispatcher::hasListeners('kernal.responese');

绑定多事件监听类

EventDispatcher::addSubscriber(EventSubscriberInterface $subscriber)
EventDispatcher::removeSubscriber(EventSubscriberInterface $subscriber)
  1. $subscriber = new TestSubscriber();
  2. EventDispatcher::addSubscriber($subscriber);
  3. EventDispatcher::hasListeners('test.start')
  4. EventDispatcher::hasListeners('test.stop')
  5. EventDispatcher::hasListeners('test.doing')
  6. EventDispatcher::dispatch('test.start');
  7. EventDispatcher::dispatch('test.stop');
  8. EventDispatcher::dispatch('test.doing');
  9. EventDispatcher::removeSubscriber($subscriber);