3

An error occurred when I tried to put the service @doctrine.orm.entity_manager as an argument for my listener UserDeletionListener.

My service:

se.doctrine_listener.user_deletion:
        class: SE\CoreBundle\DoctrineListener\UserDeletionListener
        arguments:
              - "@doctrine.orm.entity_manager"
        tags:
            - { name: doctrine.event_listener, event: preRemove }

My listener:

namespace SE\CoreBundle\DoctrineListener;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\EntityManager;
use SE\UserBundle\Entity\User;

class UserDeletionListener
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    public function __construct(EntityManager $entityManager)
    {
        $this->em = $entityManager;
    }
/...

Here is the error:

Circular reference detected for service "doctrine.dbal.default_connection", path: "doctrine.dbal.default_connection".
BSMP
  • 4,596
  • 8
  • 33
  • 44
Lenny4
  • 1,215
  • 1
  • 14
  • 33
  • 3
    You shouldn't need to inject the entity manager into a doctrine event listener - you can get it in the corresponding callback (`preRemove` in your case) using the LifecycleEventArgs argument. – ccKep Sep 15 '17 at 00:39
  • For further reading, see [Creating the Listener Class](http://symfony.com/doc/current/doctrine/event_listeners_subscribers.html#creating-the-listener-class), specifically: *In each event, you have access to a LifecycleEventArgs object, which gives you access to both the entity object of the event and the entity manager itself.* – ccKep Sep 15 '17 at 00:44
  • And the reason for the error is the way the container initializes the entity manager and the listeners. The manager is dependent on the listeners so making a listener dependent on the manager will cause a circular reference. Pasting your error message into a browser search bar will give you the same explanation. And by the way, if you are tempted to access the entity manager in a listener then what you trying to do probably won't work anyways. Doctrine events are extremely limited. – Cerad Sep 15 '17 at 00:53

2 Answers2

7

when you use EventArgs {lifecycle, preUpdate, etc...], you don't have to pass doctrine.orm.entity_manager anymore :-D You can get it by the method getEntityManager of the eventArgs itself

JessGabriel
  • 1,062
  • 9
  • 18
3

Add Lazy loading to doctrine Event Listener

* - { name: doctrine.event_listener, event: preRemove, lazy: true }