Contributte Event Dispatcher

Content

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

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
1
extensions:
    events: Contributte\EventDispatcher\DI\EventDispatcherExtension
1
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

Autoload

If you would like to add all subscribers by yourself, you have to disable autoload.

events:
    autoload: true/false
1
2

Laziness

Lazy options is enabled (true) as default. But you can override it.

events:
    lazy: true/false
1
2

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...
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Dispatcher

This little snippet explain the cycle of event dispatcher.

use Symfony\Component\EventDispatcher\EventDispatcher;

$dispatcher = new EventDispatcher();

// Register subscriber (this happens automatically during DIC compile time)
$dispatcher->addSubscriber(new OrderLoggerSubscriber());

// Dispatching event (this should be in your service layer)
$dispatcher->dispatch(new OrderCreatedEvent());
$dispatcher->dispatch(new OrderUpdatedEvent());
$dispatcher->dispatch(new OrderPaidEvent());
1
2
3
4
5
6
7
8
9
10
11

Extra

The goal of this library is to be the most tiniest and purest adaptation of Symfony Event-Dispatcher to Nette Framework.

As you can see only one Extension class is provided. Nette has many single packages and here comes the event-dispatcher-extra package.

This extra repository contains useful events for application, latte and many others. Take a look.

Compatibility

How to make this extension work with other Symfony/EventDispatcher implementations.

Kdyby/Events

Kdyby/Events has a conflict with this package because of it's SymfonyDispatcher proxy class. To avoid the conflict simply add this to your config.neon:

services:
    events.symfonyProxy:
        autowired: off
1
2
3