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\Attribute\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\Attribute\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
.
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.
What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...