Event Listeners
In opposite to Entity Listeners, Event listeners are services that listen for all entities in your application.
See https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#implementing-event-listeners for more info on event listeners.
To register a service to act as an event listener you have to tag it with the
doctrine.event_listener tag:
Starting with Doctrine bundle 2.8, you can use the AsDoctrineListener
attribute to tag the service.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// src/App/EventListener/SearchIndexer.php
namespace App\EventListener;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
#[AsDoctrineListener('postPersist'/*, 500, 'default'*/)]
class SearchIndexer
{
public function postPersist(LifecycleEventArgs $event): void
{
// ...
}
}
Ordering Listeners
With symfony/doctrine-bridge 8.2 or higher, a listener can specify which
other listeners of the same event it should run before or after, as
service ids or classes, instead of relying on the priority option:
1 2
#[AsDoctrineListener('postPersist', after: AuditLogger::class)]
class SearchIndexer
The doctrine.event_listener tag accepts the same before and after
options. With older versions of symfony/doctrine-bridge, the tag ignores
them, and the attribute throws an exception.
When declared, priority is kept: before and after only change the
order of listeners that have the same priority. The container fails to compile
when they contradict the priorities, for example when a listener should run
before another one that has a higher priority. A listener without a
priority is placed according to its before and after options.
before and after ignore the listeners of other events and connections.