@@ -1029,14 +1029,7 @@ It's important to check if the user is authenticated first. If they're not,
1029
1029
``$user `` will either be ``null `` or the string ``anon. ``. Wait, what? Yes,
1030
1030
this is a quirk. If you're not logged in, the user is technically the string
1031
1031
``anon. ``, though the ``getUser() `` controller shortcut converts this to
1032
- ``null `` for convenience. When type-hinting the
1033
- :class: `Symfony\\ Component\\ Security\\ Core\\ User\\ UserInterface\\ UserInterface `
1034
- and being logged-in is optional, you can allow a null value for the argument::
1035
-
1036
- public function indexAction(UserInterface $user = null)
1037
- {
1038
- // $user is null when not logged-in or anon.
1039
- }
1032
+ ``null `` for convenience.
1040
1033
1041
1034
The point is this: always check to see if the user is logged in before using
1042
1035
the User object, and use the ``isGranted() `` method (or
@@ -1052,6 +1045,25 @@ the User object, and use the ``isGranted()`` method (or
1052
1045
1053
1046
}
1054
1047
1048
+ .. note ::
1049
+
1050
+ An alternative way to get the current user in a controller is to type-hint
1051
+ the controller argument with
1052
+ :class: `Symfony\\ Component\\ Security\\ Core\\ User\\ UserInterface\\ UserInterface `
1053
+ (and default it to ``null `` if being logged-in is optional)::
1054
+
1055
+ use Symfony\Component\Security\Core\User\UserInterface\UserInterface;
1056
+
1057
+ public function indexAction(UserInterface $user = null)
1058
+ {
1059
+ // $user is null when not logged-in or anon.
1060
+ }
1061
+
1062
+ This is only recommended for experienced developers who don't extend from the
1063
+ :ref: `Symfony base controller <the-base-controller-class-services >` and
1064
+ don't use the :class: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ ControllerTrait `
1065
+ either. Otherwise, keep usin the recommended ``getUser() `` shortcut.
1066
+
1055
1067
Retrieving the User in a Template
1056
1068
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1057
1069
0 commit comments