Symfony News

New in Symfony 5.2: Controller argument attributes

Jérôme Vasseur

Contributed by
Jérôme Vasseur
in #37829.

PHP 8 will be released in a few weeks and it will include a game changer feature called attributes (or annotations). Symfony 5.2 already includes attributes to define routes and required dependencies, but we continued adding attributes support where it makes sense.

That’s why in Symfony 5.2 you can also use PHP attributes for controller arguments. Thanks to this new feature, we’ve introduced a #[CurentUser] attribute to turn a controller argument into the object the represents the currently logged user:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// src/Controller/SomeController.php
namespace App\Controller;

use App\Entity\MyUser;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class SomeController extends AbstractController
{
    public function index(#[CurrentUser] MyUser $user)
    {
        // ...
    }
}

In practice, this works by adding a new method to the ArgumentMetadata object passed to the argument value resolvers. If you define your own resolvers, you can now use the getAttribute() method, which returns the attribute that was set on the argument (or null if none was set).


Sponsor the Symfony project.


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