I have started to learn Symfony (4.1) and I have a question about annotations.
As far as I know, annotation are just comments in terms of php and they are not a part of the language itself. However they are rather powerful thing in Symfony.
I want to know, how it all works.
Put simply, I would like to know how do annotations in Symfony work, the mechanism of this feature.
Symfony uses the Doctrine Annotations module to parse the docblock from your class. See: https://github.com/doctrine/annotations. https://www.doctrine-project.org/projects/doctrine-annotations/en/current/index.html. It uses Reflection class to read the annotations.
PHP annotations are basically metadata which can be included in the source code and also in between classes, functions, properties and methods. They are to be started with the prefix @ wherever they are declared and they indicate something specific.
When your application receives a request, it calls a controller action to generate the response. The routing configuration defines which action to run for each incoming URL. It also provides other useful features, like generating SEO-friendly URLs (e.g. /read/intro-to-symfony instead of index.
Yes, indeed, annotations are not part of the language itself. But they're also not the part of Symfony framework.
Annotations are usually handled by doctrine/annotations
package (most common). It utilizes reflection to read and parse these comments and transform them into annotation objects (every annotation has an annotation class which it represents).
Then, its up to the library to make use of generated objects representing these annotations.
So to answer first question - yes, there is a preprocessor. But it doesn't "create new php entities", because its the job for the library that uses those annotations (e.g. Symfony framework or Doctrine ORM).
How it affects the performance, depends on the library that uses them. If they would be parsed on every request, that would indeed affect performance. So e.g. Symfony and Doctrine ORM cache this data or create proxy classes etc.
So the answer to second question is - it might if used incorrectly, but it usually is not (in production environment) as they are simply not parsed every time.
The last question doesn't really relates to annotations. Since annotations are really classes, the reason for namespacing them is also the same. To avoid conflicts between libraries and for sake of readability.
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