New in Symfony 3.2: User value resolver for controllers
Contributed by
Lynn 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.
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
New in Symfony 3.2: User value resolver for controllers symfony.com/index.php/blog/new-in-symfony-3-2-user-value-resolver-for-controllers
Tweet thisComments
This can be used in any service with ease.
Great job!
`
/** @var MyUserClass $user */
$user = $this->getUser();
`
Which is better for autocompletion.
/**
* @method MyUserClass getUser()
*/
So I got autocompletion for the user methods in all my controller classes.
* @param UserInterface|MyUserClass $user
I agree that injecting the user object as a parameter, instead of calling $this->getUser(), feels cleaner and easier to test.
```
indexAction(UserInterface $user, Request $request) {}
```
Everything that result in less methods in BaseController is a win.
:/
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Angel Koilov said on Jul 13, 2016 at 07:18 #1
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 :)