Contributed by
Iltar van der Berg
in #18510.
In Symfony applications, controllers that make use of the base Controller class
can get the object that represents the current user via the getUser() shortcut:
1 2 3 4 5 6 7 8 9 10 | use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
$user = $this->getUser();
// ...
}
}
|
In the past, you could also get the current request object with the getRequest()
shortcut, which was deprecated in Symfony 2.4 in favor of the Request type-hint:
1 2 3 4 5 6 7 | use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
public function indexAction(Request $request) { ... }
}
|
In Symfony 3.2, we've added a new user resolver that allows to get the
current user in any controller via type-hinting and we deprecated the
Controller::getUser() shortcut, which will be removed in Symfony 4.0:
1 2 3 4 5 6 7 8 9 10 11 | use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\User\UserInterface;
class DefaultController extends Controller
{
// when the user is mandatory (e.g. behind a firewall)
public function fooAction(UserInterface $user) { ... }
// when the user is optional (e.g. can be anonymous)
public function barAction(UserInterface $user = null) { ... }
}
|
This feature uses the argument resolver extension mechanism that was introduced in Symfony 3.1. This mechanism allows to register your own value resolvers for controller arguments.


Comments
These mini update notifications posts are pretty cool.
Am I the only one seeing more changes in 3.1 -> 3.2 than in 2.8 -> 3.0 :)
Can `UserInterface` type be changed by a custom one?
This can be used in any service with ease.
Great job!