Introduction
The Doctrine Event Manager is a simple event system used by the various Doctrine projects. It was originally built for the DBAL and ORM but over time other projects adopted it and now it is available as a standalone library.
Installation
The library can easily be installed with composer.
$ composer require doctrine/event-manager
Listeners
Now you are ready to listen for events. Here is an example of a custom event listener named TestEvent
.
1 use Doctrine\Common\EventArgs;
use Doctrine\Common\EventManager;
final class TestEvent
{
public const preFoo = 'preFoo';
public const postFoo = 'postFoo';
/** @var EventManager */
private $eventManager;
/** @var bool */
public $preFooInvoked = false;
/** @var bool */
public $postFooInvoked = false;
public function __construct(EventManager $eventManager)
{
$eventManager->addEventListener([self::preFoo, self::postFoo], $this);
}
public function preFoo(EventArgs $eventArgs) : void
{
$this->preFooInvoked = true;
}
public function postFoo(EventArgs $eventArgs) : void
{
$this->postFooInvoked = true;
}
}
// Create a new instance
$testEvent = new TestEvent($eventManager);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Removing Event Listeners
You can easily remove a listener with the removeEventListener()
method.
1 $eventManager->removeEventListener([TestEvent::preFoo, TestEvent::postFoo], $testEvent);
Event Subscribers
The Doctrine event system also has a simple concept of event subscribers. We can define a simple TestEventSubscriber
class which implements the Doctrine\Common\EventSubscriber
interface with a getSubscribedEvents()
method which returns an array of events it should be subscribed to.
1 use Doctrine\Common\EventSubscriber;
final class TestEventSubscriber implements EventSubscriber
{
/** @var bool */
public $preFooInvoked = false;
public function preFoo() : void
{
$this->preFooInvoked = true;
}
public function getSubscribedEvents() : array
{
return [TestEvent::preFoo];
}
}
$eventSubscriber = new TestEventSubscriber();
$eventManager->addEventSubscriber($eventSubscriber);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
The array returned by the |
Now when you dispatch an event, any event subscribers will be notified of that event.
1 $eventManager->dispatchEvent(TestEvent::preFoo);
Now you can check the preFooInvoked
property to see if the event subscriber was notified of the event: