How to get the current logged User in a service

前端 未结 7 1134
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 20:25

In Symfony 2.8/3.0, with our fancy new security components, how do I get the currently logged User (i.e. FOSUser) object in a service without

7条回答
  •  时光说笑
    2020-12-03 21:16

    Using constructor dependency injection, you can do it this way:

    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class A
    {
        private $user;
    
        public function __construct(TokenStorageInterface $tokenStorage)
        {
            $this->user = $tokenStorage->getToken()->getUser();
        }
    
        public function foo()
        {
            dump($this->user);
        }
    }
    

提交回复
热议问题