Symfony get connected user id from entity

后端 未结 3 1384
无人共我
无人共我 2021-01-25 12:53

In a Symfony2.8/Doctrine2 application, I need to store in each row of my SQL tables the id of the user who created or updated the row (users can connect with Ldap).

So al

相关标签:
3条回答
  • 2021-01-25 13:22

    You can use a Doctrine entity listener/subscriber instead and to inject the security token and gets the current user logged:

    // src/AppBundle/EventListener/EntityListener.php
    namespace AppBundle\EventListener;
    
    use Doctrine\ORM\Event\LifecycleEventArgs;
    use AppBundle\Entity\GenericEntity;
    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class EntityListener
    {
        private $tokenStorage;
    
        public function __construct(TokenStorageInterface $tokenStorage = null) 
        {
            $this->tokenStorage = $tokenStorage;
        }
    
        public function prePersist(LifecycleEventArgs $args)
        {
            $entity = $args->getEntity();
    
            // only act on some "GenericEntity" entity
            if (!$entity instanceof GenericEntity) {
                return;
            }
    
            if (null !== $currentUser = $this->getUser()) {
                $entity->setCreationId($currentUser->getId());
            } else {
                $entity->setCreationId(0);
            }
        }
    
        public function getUser()
        {
            if (!$this->tokenStorage) {
                throw new \LogicException('The SecurityBundle is not registered in your application.');
            }
    
            if (null === $token = $this->tokenStorage->getToken()) {
                return;
            }
    
            if (!is_object($user = $token->getUser())) {
                // e.g. anonymous authentication
                return;
            }
    
            return $user;
        }
    }
    

    Next register you listener:

    # app/config/services.yml
    services:
        my.listener:
            class: AppBundle\EventListener\EntityListener
            arguments: ['@security.token_storage']
            tags:
                - { name: doctrine.event_listener, event: prePersist }
    
    0 讨论(0)
  • 2021-01-25 13:25

    You can look at BlameableListener from gedmo/doctrine-extensions package, that work almost the way you want but with the username instead of the user id.

    0 讨论(0)
  • 2021-01-25 13:32

    @ORM\PrePersist and other callback methods used in the entity are suppose to contain simple logic and be independant of other services.

    You need to create event listener or subscriber to listen postPersist doctrine event and fill in corresponding attribute. Check How to Register Event Listeners and Subscribers

    0 讨论(0)
提交回复
热议问题