Event registration

Swoft provides easy event use

annotation

Listener

Event listener class annotation tag @Listener

  • Annotation class: Swoft\Event\Annotation\Mapping\Listener
  • Scope: CLASS
  • Have attributes:
    • event string The name of the event to listen to
    • priority int The priority this listener. The larger the value, the earlier the call is called.

Note that your class must implement the interface: Swoft\Event\EventHandlerInterface

Subscriber

The event listener class annotation tag @Subscriber , unlike @Listener , allows multiple events to be handled in the same class.

  • Annotation class: Swoft\Event\Annotation\Mapping\Subscriber
  • Scope: CLASS

Note that your class must implement the interface: Swoft\Event\EventSubscriberInterface

Example

Listener example

<?php declare(strict_types=1);

namespace SwoftTest\Event\Testing;

use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;

/**
 * Class TestHandler
 * @Listener("test.evt")
 */
class TestHandler implements EventHandlerInterface
{
    /**
     * @param EventInterface $event
     */
    public function handle(EventInterface $event): void
    {
        $pos = __METHOD__;
        echo "handle the event '{$event->getName()}' on the: $pos\n";
    }
}

Subscriber示例

<?php declare(strict_types=1);

namespace SwoftTest\Event\Testing;

use Swoft\Event\Annotation\Mapping\Subscriber;
use Swoft\Event\EventInterface;
use Swoft\Event\EventSubscriberInterface;
use Swoft\Event\Listener\ListenerPriority;

/**
 * Class TestSubscriber
 * @Subscriber()
 */
class TestSubscriber implements EventSubscriberInterface
{
    public const EVENT_ONE = 'test.event1';
    public const EVENT_TWO = 'test.event2';

    /**
     * Configure events and corresponding processing methods (you can configure the priority)
     * @return array
     * [
     *  'event name' => 'handler method'
     *  'event name' => ['handler method', priority]
     * ]
     */
    public static function getSubscribedEvents(): array
    {
        return [
            self::EVENT_ONE => 'handleEvent1',
            self::EVENT_TWO => ['handleEvent2', ListenerPriority::HIGH],
        ];
    }

    public function handleEvent1(EventInterface $evt): void
    {
        $evt->setParams(['msg' => 'handle the event: test.event1 position: TestSubscriber.handleEvent1()']);
    }

    public function handleEvent2(EventInterface $evt): void
    {
        $evt->setParams(['msg' => 'handle the event: test.event2 position: TestSubscriber.handleEvent2()']);
    }
}

触发事件

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

\Swoft::trigger('event name', null, $arg0, $arg1);
/docs/2.x/en/event/usage.html
progress-bar