@@ -1007,16 +1007,14 @@ If you still prefer to use traditional ACLs, refer to the `Symfony ACL bundle`_.
10071007-----------------------------
10081008
10091009After authentication, the ``User `` object of the current user can be accessed
1010- via the ``security.token_storage `` service. From inside a controller, this will
1011- look like::
1010+ via the ``getUser() `` shortcut (which uses the `` security.token_storage ``
1011+ service). From inside a controller, this will look like::
10121012
10131013 public function index()
10141014 {
10151015 $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
10161016
10171017 $user = $this->getUser();
1018- // or you can also type-hint a method argument with this class:
1019- // Symfony\Component\Security\Core\User\UserInterface (e.g. "UserInterface $user")
10201018 }
10211019
10221020.. tip ::
@@ -1044,14 +1042,7 @@ It's important to check if the user is authenticated first. If they're not,
10441042``$user `` will either be ``null `` or the string ``anon. ``. Wait, what? Yes,
10451043this is a quirk. If you're not logged in, the user is technically the string
10461044``anon. ``, though the ``getUser() `` controller shortcut converts this to
1047- ``null `` for convenience. When type-hinting the
1048- :class: `Symfony\\ Component\\ Security\\ Core\\ User\\ UserInterface\\ UserInterface `
1049- and being logged-in is optional, you can allow a null value for the argument::
1050-
1051- public function index(UserInterface $user = null)
1052- {
1053- // $user is null when not logged-in or anon.
1054- }
1045+ ``null `` for convenience.
10551046
10561047The point is this: always check to see if the user is logged in before using
10571048the User object, and use the ``isGranted() `` method (or
@@ -1065,6 +1056,25 @@ the User object, and use the ``isGranted()`` method (or
10651056 // ...
10661057 }
10671058
1059+ .. note ::
1060+
1061+ An alternative way to get the current user in a controller is to type-hint
1062+ the controller argument with
1063+ :class: `Symfony\\ Component\\ Security\\ Core\\ User\\ UserInterface\\ UserInterface `
1064+ (and default it to ``null `` if being logged-in is optional)::
1065+
1066+ use Symfony\Component\Security\Core\User\UserInterface\UserInterface;
1067+
1068+ public function indexAction(UserInterface $user = null)
1069+ {
1070+ // $user is null when not logged-in or anon.
1071+ }
1072+
1073+ This is only recommended for experienced developers who don't extend from the
1074+ :ref: `Symfony base controller <the-base-controller-class-services >` and
1075+ don't use the :class: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ ControllerTrait `
1076+ either. Otherwise, it's recommended to keep using the ``getUser() `` shortcut.
1077+
10681078Retrieving the User in a Template
10691079~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10701080
0 commit comments