Skip to content

Events

The event system consists of an event dispatcher and event subscribers.

Subscribers subscribe to particular events and are executed after the events are dispatched. Their execution can be prioritized. Subscribers receive an event object that implements Amarant\Framework\Contract\Event\EventInterface. The object can be used to store any data and to stop execution of the next subscribers, using the stop method.

Events are widely used to allow other parts of the application to react to the data of an event object.

Note

Event objects usually have other publicly exposed methods other than the ones present in the EventInterface. That's why subscriber methods that handle a particular event usually expect a very specific event object type in a method signature.

Create an event subscriber


In the following example, a subscriber for the http application request event is created.
Check the annotations to know more.

Vendor/ModuleName/EventSubscriber/RequestSubscriber.php
<?php

declare(strict_types=1);

namespace Vendor\ModuleName\EventSubscriber;

use Amarant\Framework\Contract\Application\ContextInterface;
use Amarant\Framework\Contract\Event\EventSubscriberInterface;
use Amarant\Framework\Data\Event\Type\Request\RequestEvent;
use Amarant\Framework\Enum\EventEnum;
use Override;

final class RequestSubscriber implements EventSubscriberInterface
{
    /**
     * @inheritDoc
     */
    // (1)
    #[Override] public static function subscribe(ContextInterface $context): ?array
    {
        return [
            // (2)
            EventEnum::APP_REQUEST->value => [
                // (3)
                400 => 'handle',
            ],
        ];
    }

    // (4)
    public function handle(RequestEvent $event): void
    {
        // do something using the received event data

        // to skip further execution of subscribers for this particular event, use:
        $event->stop();
    }
}
  1. Using this method, the subscriber subscribes to one or more events. Null can be returned, if for example the subscriber decides not to subscribe, depending on the application context.
  2. The event name to subscribe to.
  3. The priority of the subscriber and the name of the handling method. Subscribers with higher priority are executed first. Check the Amarant\Framework\Enum\EventPriorityEnum to see core priority values.
  4. The handling method that receives the specific event object, depending on the event type, in this case the request event.

Important

Always use Amarant\Framework\Enum\EventEnum or enums/constants in other application modules when referring to event names. Never hardcode event names.

Tag the new subscriber with dependency injection configurator.

Dependency injection tags

Amarant\Framework\Enum\DiEnum::EVENT_SUBSCRIBER

Note

To subscribe to events only in a particular application area, use area-specific configuration.