Symfony2: How to get user Object inside controller when using FOSUserBundle?

后端 未结 8 1856
别跟我提以往
别跟我提以往 2020-12-28 13:04

I\'m using FOSUserBundle to authenticate my users.

I\'m trying to get the user object inside the Controller to register a trip where I should add the user object to

8条回答
  •  攒了一身酷
    2020-12-28 13:19

    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.

    Here is blog post about it

提交回复
热议问题