The new (Symfony 6) way of listening to events with Symfony now exclude the Doctrine subscribers. However, those are still a thing and may be interesting if you want to listen on all entities, or if you want to add a feature in a bundle outside of the scope of a project...! And it's working with Symfony 6.
This however does not work in Symfony7 anymore. See below to the new way of creating a global subscriber.
If the EventSubscriberInterface of the doctrine bundle is deprecated, it's not the case of the related tag. So you still can make a custom Doctrine subscriber easily.
Here is an example:
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
class PostLoadSubscriber implements EventSubscriber
{
public function getSubscribedEvents()
{
return ['postLoad'];
}
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getObject();
// Do your stuff here
}
}
And the configuration you should add is simple.
services:
You\PostLoadSubscriber:
tags:
- { name: doctrine.event_subscriber }
You can find an event overview here: https://www.doctrine-project.org/projects/doctrine-orm/en/3.2/reference/events.html#events-overview
There is no more support for Doctrine event subscribers in Symfony. You need to define it as listener. Here is how to transform our previously created subcriber to a listener:
getSubscribedEvents
methoduse Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
class PostLoadListener
{
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getObject();
// Do your stuff here
}
}
Then change the configuration as well to specify it's a listener:
services:
You\PostLoadListener:
tags:
# You can optionally add the options:
# - entity_manager (defaults to "default")
# - method (the method name to be called)
# - lazy
- { name: doctrine.event_listener, event: postLoad }