Using constants in PHP 8 attributes

Published on 2022-06-25 • Modified on 2022-06-25

This snippet shows how to use constants in PHP 8 attributes. It is an excellent pro that PHP 8 attributes provide. Before, we had to use plain text in annotations which could be error-prone (and also annoying to write). For example, before we used something like this in a controller @IsGranted("ROLE_ADMIN"), the role was hardcoded. And, if the ROLE_ADMIN changed, you had to modify its name in all your code. That's not the case with the attributes. We can introduce a new constant in a User: class public const ROLE_ADMIN = 'ROLE_ADMIN';, and use it now in our attribute like below. We can also use class name constants like shown in the Stackoverflow question.


    /**
     * @see ApiControllerTest::testTestSecured()
     */
    #[Route(path: '/api/secured', name: 'api_secured')]
    #[IsGranted(User::ROLE_ADMIN)]
    public function testSecured(): Response
    {
        return $this->json(['OK' => true]);
    }

 More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!