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

后端 未结 8 1789
别跟我提以往
别跟我提以往 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:16

    For FOSUser ^1.3 you can get current user from inside a controller that extends BaseController like this :

    $user = $this->container->get('security.token_storage')->getToken()->getUser();
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-28 13:22

    I think Ramon is right. You already have the user object.

    Also in Symfony > 2.1.x you can use

    $this->getUser();
    

    inside the controller.

    0 讨论(0)
  • 2020-12-28 13:24
    public function indexAction()
    {
        /* @var $user \FOS\UserBundle\Model\UserInterface */
        if ($user = $this->getUser())
        {
            echo '<pre>';
            print_r($user);
            print_r($user->getRoles()); // method usage example
    
            exit;
    
            return $this->redirectToRoute('dashboard');
        }
    
        return $this->redirectToRoute('login');
    }
    
    0 讨论(0)
  • 2020-12-28 13:26

    I had the same issue, to resolve it add the FOS classes in your use section i.e:

    use FOS\UserBundle\FOSUserEvents;
    use FOS\UserBundle\Event\GetResponseUserEvent;
    use FOS\UserBundle\Model\UserInterface;
    
    0 讨论(0)
  • 2020-12-28 13:30

    The documentation for the getUser method indicates:

    either returns an object which implements __toString(), or a primitive string is returned.

    And if we look in the FOS\UserBundle\Model\User class over here (the base user class used by the FOSUserBundle) we can see that it does indeed have a __toString method:

    public function __toString()
    {
        return (string) $this->getUsername();
    }
    

    I think that you actually get the User object but because it implements a __toString method it can be rendered directly in templates.

    In Twig you can use:

    {{ dump(user) }}
    

    To see what kind of object you have. But You are actually using an object, not a string.

    0 讨论(0)
提交回复
热议问题