Symfony News

New in Symfony 3.2: User value resolver for controllers

Iltar van der Berg

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.


Be trained by Symfony experts - 2016-07-18 Paris - 2016-07-18 Paris - 2016-07-20 Paris


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook