New in Symfony 5.2: Controller argument attributes

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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).
Help the Symfony project!
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.
Comments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Thanks to attributes, you can also pass "configuration options" to those arguments. You could for example create the "#[Autowire]" attribute to define your own autowiring mechanism, or you could define "#[SomeAttribute(SomeClass::class, Some_CONSTANT, 24 * 3600)]" to evaluate expressions and constants and pass them to the resolvers.
https://wiki.php.net/rfc/attributes_v2