New in Symfony 5.2: Constraints as PHP attributes
October 20, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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.
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 are closed.
To ensure that comments stay relevant, they are closed for old posts.