Symfony2 - $this->getUser() vs $this->get('fos_user.user_manager');

11,844

Solution 1

With $this->getUser() is only a shortcut to

$this->get('security.context')->getToken()->getUser()

So this means you get the user object according to the current security token. It's perfect and easy, when you want to retrieve the actual logged in user.

But if you want to get other users, fos_user.user_manager is the choice, as it has methods to find users easy and hiding the implementation behind. And it provides also methods for creating new users and updating them. And also if you retrieve the current logged in user with $this->getUser() and made modifcations to them, you should use the fos user manager to update them. Take a look in the docs for more!

Solution 2

They return different objects. $this->get('fos_user.user_manager') returns a FOS\UserBudle\Doctrine\UserManager object and $this->getUser() returns a FOS\UserBundle\Model\User object. The former handles users and the latter is a user. So no, you are using it right.

Solution 3

Where the two differ is in saving a user or creating a new user. If using the FOSUserBundle, you should always use the $this->get('fos_user.user_manager') method. This gives you access to the updateUser() function that works with the FOSUserBundle to make sure it updates all the user attributes that you don't need to explicitly declare in your User model, like date_created and roles.

That function is different than using Doctrine to persist() and then flush() the model.

Share:
11,844
user2143356
Author by

user2143356

Updated on June 15, 2022

Comments

  • user2143356
    user2143356 almost 2 years

    I'm using FOSUserBundle. What is the difference between these two?

    $this->get('fos_user.user_manager');
    

    ...and...

    $this->getUser();
    

    I've found I've used both of the above at different times and everything works fine.

    I'm guessing the first one is from FOS and the second one is the default one, but I'm guessing I should always use the same one.

    This is one piece of code I've used:

    $user = $this->getUser();
    if($user) {             
        $email = $user->getEmail();
    } else {
        $email = "no email";
    }
    

    ..and another...

    $userManager = $this->get('fos_user.user_manager');
    $user = $userManager->findUserBy(array('memberID' => '123'));
    

    ...so should I have used the same method for both?