Event Registration

Swoft provides easy event usage

Annotations

Listener

Event Listener Class Annotation Tag@Listener

  • Annotation class:Swoft\Event\Annotation\Mapping\Listener
  • Scope of Action:CLASS
  • Owning attributes:
    • eventString The event name to listen to
    • priorityInt The priority of this listener, the greater the value, the more it is called first

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

Subscriber

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 of Action:CLASS

Note that your class must implement an 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 example

<?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()']);
    }
}

Trigger Event

Event name management is recommended to be placed in a separate class of constants for easy management and maintenance

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