Symfony News

New in Symfony 5.2: Constraints as PHP attributes

Alexander M. Turek

Contributed by
Alexander M. Turek
in #38309 and #38499.

PHP 8 will be released in a few weeks and it will include a game changer feature called attributes (or annotations). In Symfony 5.2 we’ve added support for defining routes as attributes and controller arguments as attributes.

Constraints seemed like the next obvious step and that’s why in Symfony 5.2 you can define validation constraints as PHP attributes. The transition has been designed to be seamless:

Before, using annotations via PHP comments and Doctrine annotations library:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// src/Entity/Author.php
namespace App\Entity;

// ...
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\Choice(
     *     choices = { "fiction", "non-fiction" },
     *     message = "Choose a valid genre."
     * )
     */
    private $genre;

    // ...
}

After, using native PHP 8 attributes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// src/Entity/Author.php
namespace App\Entity;

// ...
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Choice(
        choices: ['fiction', 'non-fiction'],
        message: 'Choose a valid genre.',
    )]
    private $genre;

    // ...
}

Most constraints have already been updated so you can use them both as annotations and attributes. However, the following composite constraints can’t be used with attributes:

  • All
  • AtLeastOneOf
  • Collection
  • Compound (abstract)
  • Existence (abstract) * Required * Optional
  • Sequentially

The reason is that they would require nested attributes and PHP doesn’t support that feature yet. We’re still discussing about what’s the best solution for this problem. Consider joining the discussion in the Issue #38503.


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