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

前端 未结 6 591
囚心锁ツ
囚心锁ツ 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:40

    In symfony >= 3.2, documentation states that:

    An alternative way to get the current user in a controller is to type-hint the controller argument with UserInterface (and default it to null if being logged-in is optional):

    use Symfony\Component\Security\Core\User\UserInterface\UserInterface;
    
    public function indexAction(UserInterface $user = null)
    {
        // $user is null when not logged-in or anon.
    }
    

    This is only recommended for experienced developers who don't extend from the Symfony base controller and don't use the ControllerTrait either. Otherwise, it's recommended to keep using the getUser() shortcut.

    Blog post about it

提交回复
热议问题