Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting SecurityContext into a Listener prePersist or preUpdate in Symfony2 to get User in a createdBy or updatedBy Causes Circular Reference Error

I setup a listener class where i'll set the ownerid column on any doctrine prePersist. My services.yml file looks like this ...

services: my.listener:     class: App\SharedBundle\Listener\EntityListener     arguments: ["@security.context"]     tags:         - { name: doctrine.event_listener, event: prePersist } 

and my class looks like this ...

use Doctrine\ORM\Event\LifecycleEventArgs; use Symfony\Component\Security\Core\SecurityContextInterface;  class EntityListener {  protected $securityContext;  public function __construct(SecurityContextInterface $securityContext) {     $this->securityContext = $securityContext; }   /**  *  * @param LifecycleEventArgs $args   */ public function prePersist(LifecycleEventArgs $args) {      $entity = $args->getEntity();     $entityManager = $args->getEntityManager();      $entity->setCreatedby();  } } 

The result of this is the following error.

ServiceCircularReferenceException: Circular reference detected for service "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> my.listener -> security.context -> security.authentication.manager -> fos_user.user_manager".

My assumption is that the security context has already been injected somewhere in the chain but I don't know how to access it. Any ideas?

like image 823
Jeremy Avatar asked Sep 26 '11 20:09

Jeremy


1 Answers

I had similar problems and the only workaround was to pass the whole container in the constructor (arguments: ['@service_container']).

use Doctrine\ORM\Event\LifecycleEventArgs; use Symfony\Component\DependencyInjection\ContainerInterface;  class MyListener {     protected $container;      public function __construct(ContainerInterface $container)     {         $this->container = $container;     }      // ...      public function prePersist(LifeCycleEventArgs $args)     {         $securityContext = $this->container->get('security.context');          // ...     } } 
like image 88
kgilden Avatar answered Sep 25 '22 17:09

kgilden