How do I get the entity that represents the current user in Symfony2?

前端 未结 6 603
囚心锁ツ
囚心锁ツ 2020-12-04 09:05

I am using the Symfony security setup. Everything works fine, but I don\'t know how to do one important thing:

In twig, I can reach the current user\'s info by doing

6条回答
  •  难免孤独
    2020-12-04 09:38

    Best practice

    According to the documentation since Symfony 2.1 simply use this shortcut :

    $user = $this->getUser();
    

    The above is still working on Symfony 3.2 and is a shortcut for this :

    $user = $this->get('security.token_storage')->getToken()->getUser();
    

    The security.token_storage service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use the getToken() method of the security.context service.

    Example : And if you want directly the username :

    $username = $this->getUser()->getUsername();
    

    If wrong user class type

    The user will be an object and the class of that object will depend on your user provider.

提交回复
热议问题