Skip to content

Commit 937979e

Browse files
committed
Added a note about type-hinting UserInterface in controllers
1 parent 58f7499 commit 937979e

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

security.rst

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1029,14 +1029,7 @@ It's important to check if the user is authenticated first. If they're not,
10291029
``$user`` will either be ``null`` or the string ``anon.``. Wait, what? Yes,
10301030
this is a quirk. If you're not logged in, the user is technically the string
10311031
``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.
10401033

10411034
The point is this: always check to see if the user is logged in before using
10421035
the User object, and use the ``isGranted()`` method (or
@@ -1052,6 +1045,25 @@ the User object, and use the ``isGranted()`` method (or
10521045

10531046
}
10541047

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+
10551067
Retrieving the User in a Template
10561068
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10571069

0 commit comments

Comments
 (0)