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

前端 未结 4 2075
遥遥无期
遥遥无期 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:36

    As of Symfony 2.6 this issue should be fixed. A pull request has just been accepted into the master. Your problem is described in here. https://github.com/symfony/symfony/pull/11690

    As of Symfony 2.6, you can inject the security.token_storage into your listener. This service will contain the token as used by the SecurityContext in <=2.5. In 3.0 this service will replace the SecurityContext::getToken() altogether. You can see a basic change list here: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service

    Example usage in 2.6:

    Your configuration:

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


    Your Listener

    namespace App\SharedBundle\Listener;
    
    use Doctrine\ORM\Event\LifecycleEventArgs;
    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class EntityListener
    {
        private $token_storage;
    
        public function __construct(TokenStorageInterface $token_storage)
        {
            $this->token_storage = $token_storage;
        }
    
        public function prePersist(LifecycleEventArgs $args)
        {
            $entity = $args->getEntity();
            $entity->setCreatedBy($this->token_storage->getToken()->getUsername());
        }
    }
    


    For a nice created_by example, you can use https://github.com/hostnet/entity-blamable-component/blob/master/src/Listener/BlamableListener.php for inspiration. It uses the hostnet/entity-tracker-component which provides a special event that is fired when an entity is changed during your request. There's also a bundle to configure this in Symfony2

    • https://github.com/hostnet/entity-tracker-component
    • https://github.com/hostnet/entity-tracker-bundle

提交回复
热议问题