Lately, the attributes RFC has passed the voting stage. How they are different from DocBlock annotations, and what benefits will they bring?
Consider simple Doctrine entity, before:
/**
* @ORM\Entity
*/
class Entity {
// …
}
After, using native PHP attributes:
#[ORM\Entity]
class Entity {
// …
}
Using Doctrine annotations, you write annotations in your docblocks: The Type part is actually a class. It must be declared in the use statements at the top of your file. Heads up! We strongly recommend using an IDE that has Doctrine annotations support. Starting with PHP 8, PHP got native annotations support.
PHP-DOC annotations do not have a fixed syntax - that is, everything after @name is interpreted differently for each type of annotation. For example, the syntax for @var is @var {type} {description}, while the syntax for @param is @param {type} {$name} {description}.
There are various kinds of annotations like the @var and @int types which can be used for specific uses as their name itself suggests. PHP annotations are used by giving @ prefix and its syntax is as follows:
Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release. Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the doctrine/annotation library.
The explanation at this part of the RFC: Why not extending Doc Comments? explains a lot of the benefits
strstr()
performance or even parsing the docblock./*
and /**
is still a very subtle source of bugs.A lot of these boil down to the fact that attributes can be checked by PHP. Tools can leverage the fact that these attributes are already-parsed metadata visible with reflection, rather than comments that need to be parsed with a custom syntax per tool. IDEs and static analysis tools will be able to guarantee correctness without having to know a specific tool's docblock annotation syntax because the attributes resolve to classes that have to exist and might have further type annotations to add checking.
So:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With