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 #[CurrentUser] attribute to turn a controller argument into the object that 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).

Published in #Living on the edge