Make sure that your server is configured with following PHP version and extensions:
- PHP 8.1+
- Spiral framework 3.0+
You can install the package via composer:
composer require spiral-packages/league-event
After package install you need to register bootloader from the package.
protected const LOAD = [
// ...
\Spiral\League\Event\Bootloader\EventBootloader::class,
];
Note If you are using
spiral-packages/discoverer
, you don't need to register bootloader by yourself.
An event can be represented by a simple class:
namespace Spiral\Router\Event;
use Spiral\Router\RouteInterface;
final class RouteFound
{
public function __construct(
public readonly RouteInterface $route
) {
}
}
$this->container->get(EventDispatcherInterface::class)->dispatch(new RouteNotFound($request));
A listener can be represented by a simple class with a method that will be called to handle the event.
The method name can be configured in the Listener attribute parameter or in the configuration file ( __invoke
by default):
namespace App\Listener;
use Spiral\Events\Attribute\Listener;
use Spiral\Router\Event\RouteFound;
class RouteListener
{
public function __invoke(RouteFound $event): void
{
// ...
}
}
// file app/config/events.php
use App\Listener\RouteListener;
use Spiral\Events\Config\EventListener;
use Spiral\Router\Event\RouteFound;
return [
'listeners' => [
// without any options
RouteFound::class => [
RouteListener::class,
],
// OR
// with additional options
RouteFound::class => [
new EventListener(
listener: RouteListener::class,
method: 'onRouteFound',
priority: 1
),
],
]
];
The attribute can be used without additional parameters. Then the method name __invoke
and the event from the type
of the method parameter will be used:
namespace App\Listener;
use Spiral\Events\Attribute\Listener;
use Spiral\Router\Event\RouteFound;
#[Listener]
class RouteListener
{
public function __invoke(RouteFound $event): void
{
// ...
}
}
All available options:
namespace App\Listener;
use Spiral\Events\Attribute\Listener;
use Spiral\Router\Event\RouteFound;
#[Listener(event: RouteFound::class, method: 'onRouteFound', priority: 1)]
class RouteListener
{
public function onRouteFound(RouteFound $event): void
{
// ...
}
}
The attribute can be used directly on the method, then the method name can be omitted:
namespace App\Listener;
use Spiral\Events\Attribute\Listener;
use Spiral\Router\Event\RouteFound;
class RouteListener
{
#[Listener(priority: 1)]
public function onRouteFound(RouteFound $event): void
{
// ...
}
}
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.