Contributte Event-dispatcher
# Content
- Setup
- Configuration
- Subscriber - example subscriber
- Dispatcher - dispatching events
- Extra - extra Nette bridge
- Compatibility
# Prologue
Contributte/EventDispatcher
brings Symfony/EventDispatcher
to your Nette applications.
Please take a look at official documentation: https://symfony.com/doc/current/components/event_dispatcher.html (opens new window)
Subscriber is class that listen on defined events and handle them.
Event is a value object that has all data.
Dispatcher is manager class that tracks all listeners and thru dispatch
method emits all events.
# Setup
composer require contributte/event-dispatcher
extensions:
events: Contributte\EventDispatcher\DI\EventDispatcherExtension
2
The extension looks for all services implementing Symfony\Component\EventDispatcher\EventSubscriberInterface
.
And automatically adds them to the event dispatcher. That's all. You don't have to be worried.
# Configuration
Default
events:
lazy: true
autoload: true
debug: false
loggers: []
2
3
4
5
# Autoload
Autoload option is enabled (true
) as default. If you would like to add all subscribers by yourself, you have to disable autoload
.
events:
autoload: true/false
2
# Lazy-loading
Lazy option is enabled (true
) as default. But you can override it.
events:
lazy: true/false
2
# Debug
Debug option is disabled (false
) as default. If you want to show Tracy panel, you have to enable it.
events:
debug: %debugMode%
2
# Logging
You can log all events via loggers. Just add logger to the configuration.
events:
loggers:
- App\Logger\FileLogger(%tempDir%/events.log)
2
3
# Subscriber
use Symfony\Contracts\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class OrderLoggerSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
OrderCreatedEvent::class => 'log',
OrderUpdatedEvent::class => 'log',
OrderPaidEvent::class => 'log',
];
}
public function log(Event $event): void
{
// Do some magic here...
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
services:
- OrderLoggerSubscriber
2
# Dispatcher
Get dispatcher from DI and dispatch your events
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class UserFacade
{
public function __construct(
private EventDispatcherInterface $eventDispatcher
)
{
}
public function createOrder(Order $order): void
{
$this->eventDispatcher->dispatch(new OrderCreatedEvent($order));
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Extra
The goal of this library is to be the simplest and purest adaptation of Symfony Event-Dispatcher (opens new window) to Nette Framework (opens new window).
As you can see only one Extension
class is provided. Nette has many single packages and here comes the event-dispatcher-extra
(opens new window) package.
This extra repository contains useful events for application, latte and many others. Take a look (opens new window).