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

前端 未结 4 2049
遥遥无期
遥遥无期 2020-11-29 01:38

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:
             


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 02:21

    There's a great answer already in this thread but everything changes. Now there're entity listeners classes in Doctrine: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners-class

    So you can add an annotation to your entity like:

    /**
     * @ORM\EntityListeners({"App\Entity\Listener\PhotoListener"})
     * @ORM\Entity(repositoryClass="App\Repository\PhotoRepository")
     */
    class Photo 
    {
        // Entity code here...
    }
    

    And create a class like this:

    class PhotoListener
    {        
        private $container;
    
        function __construct(ContainerInterface $container)
        {
            $this->container = $container;
        }
    
        /** @ORM\PreRemove() */
        public function preRemoveHandler(Photo $photo, LifecycleEventArgs $event): void
        {
             // Some code here...
        }
    }
    

    Also you should define this listener in services.yml like that:

    photo_listener:
      class: App\Entity\Listener\PhotoListener
      public: false
      autowire: true
      tags:
        - {name: doctrine.orm.entity_listener}
    

提交回复
热议问题