Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 5.2: Constraints as PHP attributes

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.

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

Wondering if the highlighting of attributes is intentional or just a bug in syntax highlighter
Sadly it's an error because the syntax highlighter doesn't support PHP attributes.
Login with SymfonyConnect to post a comment