Search code examples
phpsymfonysymfony4

Symfony4 UserInterface missing ->getId() how to access users id


Why is there no getId() method inside the UserInterface in Symfony 4? I tried to pass UserInterface $user to my Controller method to actually access the current logged in user's id with $user->getId().

But this method simply doesn't exist inside this interface - talking about best practice I should not simply add this method to the interface, right?

I also tried to use my entity but was not able to access the current user object to fetch the id of the object.

First time sf4, am I getting it totally wrong?


Solution

  • Symfony's UserInterface is part of the Security Component. The Security Component only cares about authentication. For the component, the username is the unique identifier of a user. It does not assume that your user has an id field. It only cares about the fields that matter for authentication purposes.

    You should not inject the UserInterface in your controller method as a dependency, since it's not a service. Instead, Symfony provides a shorcut via the $this->getUser() method. That is typehinted to return a UserInterface. If you want typehinting to your concrete implementation, simply add on top of your controller class name as a docblock: @method User|null getUser().

    EDIT:

    Added the null in the @method User|null getUser() so you are aware that that call may return null if there's no authenticated user. This will also help code intelligence tools to warn you against null pointer exceptions.