New in Symfony 5.2: PHP 8 attributes
September 28, 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.
Contributed by
Alexander M. Turek
in #37474
and #37545.
PHP 8 is packed with new interesting features, such as union types, match expressions and constructor property promotion. However, the most sought-after new feature is built-in attributes (also called annotations).
Symfony 5.2 will include support for PHP 8 attributes to define routes and required dependencies. If you already use annotations, the transition will be seamless:
1 2 3 4 5 6 7 8 9 10 11 12 13
// BEFORE: annotations defined with Doctrine Annotations library
use Symfony\Component\Routing\Annotation\Route;
class SomeController
{
/**
* @Route("/path", name="action")
*/
public function someAction()
{
// ...
}
}
1 2 3 4 5 6 7 8 9 10 11
// AFTER: annotations defined with PHP 8 attributes
use Symfony\Component\Routing\Annotation\Route;
class SomeController
{
#[Route('/path', name: 'action')]
public function someAction()
{
// ...
}
}
The same Route
class provides support for Doctrine annotations and PHP
attributes, so you don't need to change the class import. The only required
change is to update the annotation syntax, which now looks like this: #[ ... ]
That's all! Your application is now using native PHP attributes and you can
uninstall dependencies like doctrine/annotations
if you don't use them elsewhere.
We also added a #[Required]
attribute to replace @Required
annotation
and tell Symfony that a property/method holds a required dependency:
1 2 3 4 5 6 7 8 9 10 11 12 13
use Symfony\Contracts\Service\Attribute\Required;
class SomeService
{
#[Required]
public Bar $bar;
#[Required]
public function setFoo(Foo $foo): void
{
// ...
}
}
PHP is entering a new golden era with the release of PHP 8 and Symfony will be fully-compatible since day one. These attributes are just the beginning and we'll add many more (e.g. for validation) in the coming weeks.
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.
Still the same ?