@@ -995,14 +995,14 @@ After authentication, the ``User`` object of the current user can be accessed
995
995
via the ``security.token_storage `` service. From inside a controller, this will
996
996
look like::
997
997
998
- public function indexAction()
998
+ use Symfony\Component\Security\Core\User\UserInterface;
999
+
1000
+ public function indexAction(UserInterface $user)
999
1001
{
1000
1002
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
1001
1003
throw $this->createAccessDeniedException();
1002
1004
}
1003
1005
1004
- $user = $this->getUser();
1005
-
1006
1006
// the above is a shortcut for this
1007
1007
$user = $this->get('security.token_storage')->getToken()->getUser();
1008
1008
}
@@ -1012,6 +1012,11 @@ look like::
1012
1012
The user will be an object and the class of that object will depend on
1013
1013
your :ref: `user provider <security-user-providers >`.
1014
1014
1015
+ .. versionadded :: 3.2
1016
+ The functionality to get the user via the method signature was added in 3.2,
1017
+ you can still retrieve it by calling ``$this->getUser() `` if you extend the
1018
+ :class: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ Controller `.
1019
+
1015
1020
Now you can call whatever methods are on *your * User object. For example,
1016
1021
if your User object has a ``getFirstName() `` method, you could use that::
1017
1022
@@ -1032,7 +1037,15 @@ It's important to check if the user is authenticated first. If they're not,
1032
1037
``$user `` will either be ``null `` or the string ``anon. ``. Wait, what? Yes,
1033
1038
this is a quirk. If you're not logged in, the user is technically the string
1034
1039
``anon. ``, though the ``getUser() `` controller shortcut converts this to
1035
- ``null `` for convenience.
1040
+ ``null `` for convenience. When type-hinting the
1041
+ :class: `Symfony\\ Component\\ Security\\ Core\\ User\\ UserInterface\\ UserInterface `
1042
+ and being logged-in is optional, you can allow a null value for the argument::
1043
+
1044
+ public function indexAction(UserInterface $user = null)
1045
+ {
1046
+ // $user is null when not logged-in or anon.
1047
+ }
1048
+
1036
1049
1037
1050
The point is this: always check to see if the user is logged in before using
1038
1051
the User object, and use the ``isGranted `` method (or
0 commit comments