事件注册

swoft提供了简便的事件使用

注解

Listener

事件监听器类注解tag @Listener

  • 注解类: Swoft\Event\Annotation\Mapping\Listener
  • 作用范围: CLASS
  • 拥有属性:
    • event string 要监听的事件名称
    • priority int 此监听器的优先级,值越大越先被调用

注意你的类必须实现接口: Swoft\Event\EventHandlerInterface

Subscriber

事件监听器类注解tag @Subscriber,与 @Listener 不同的是,允许在同一个类里处理多个事件。

  • 注解类: Swoft\Event\Annotation\Mapping\Subscriber
  • 作用范围: CLASS

注意你的类必须实现接口: Swoft\Event\EventSubscriberInterface

示例

Listener示例

  1. <?php declare(strict_types=1);
  2. namespace SwoftTest\Event\Testing;
  3. use Swoft\Event\Annotation\Mapping\Listener;
  4. use Swoft\Event\EventHandlerInterface;
  5. use Swoft\Event\EventInterface;
  6. /**
  7. * Class TestHandler
  8. * @Listener("test.evt")
  9. */
  10. class TestHandler implements EventHandlerInterface
  11. {
  12. /**
  13. * @param EventInterface $event
  14. */
  15. public function handle(EventInterface $event): void
  16. {
  17. $pos = __METHOD__;
  18. echo "handle the event '{$event->getName()}' on the: $pos\n";
  19. }
  20. }

Subscriber示例

  1. <?php declare(strict_types=1);
  2. namespace SwoftTest\Event\Testing;
  3. use Swoft\Event\Annotation\Mapping\Subscriber;
  4. use Swoft\Event\EventInterface;
  5. use Swoft\Event\EventSubscriberInterface;
  6. use Swoft\Event\Listener\ListenerPriority;
  7. /**
  8. * Class TestSubscriber
  9. * @Subscriber()
  10. */
  11. class TestSubscriber implements EventSubscriberInterface
  12. {
  13. public const EVENT_ONE = 'test.event1';
  14. public const EVENT_TWO = 'test.event2';
  15. /**
  16. * Configure events and corresponding processing methods (you can configure the priority)
  17. * @return array
  18. * [
  19. * 'event name' => 'handler method'
  20. * 'event name' => ['handler method', priority]
  21. * ]
  22. */
  23. public static function getSubscribedEvents(): array
  24. {
  25. return [
  26. self::EVENT_ONE => 'handleEvent1',
  27. self::EVENT_TWO => ['handleEvent2', ListenerPriority::HIGH],
  28. ];
  29. }
  30. public function handleEvent1(EventInterface $evt): void
  31. {
  32. $evt->setParams(['msg' => 'handle the event: test.event1 position: TestSubscriber.handleEvent1()']);
  33. }
  34. public function handleEvent2(EventInterface $evt): void
  35. {
  36. $evt->setParams(['msg' => 'handle the event: test.event2 position: TestSubscriber.handleEvent2()']);
  37. }
  38. }

触发事件

事件名称管理推荐放置在一个单独类的常量里面,方便管理和维护

  1. \Swoft::trigger('event name', null, $arg0, $arg1);