How to get the current logged User in a service

前端 未结 7 1120
爱一瞬间的悲伤
爱一瞬间的悲伤 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:17

    Symfony does this in Symfony\Bundle\FrameworkBundle\ControllerControllerTrait

    protected function getUser()
    {
        if (!$this->container->has('security.token_storage')) {
            throw new \LogicException('The SecurityBundle is not registered in your application.');
        }
    
        if (null === $token = $this->container->get('security.token_storage')->getToken()) {
            return;
        }
    
        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }
    
        return $user;
    }
    

    So if you simply inject and replace security.token_storage, you're good to go.

提交回复
热议问题