Doctrine Annotations allows to implement custom annotation functionality for PHP classes.
Annotations aren't implemented in PHP itself which is why this component
offers a way to use the PHP doc-blocks as a place for the well known
annotation syntax using the
Annotations in Doctrine are used for the ORM configuration to build the class mapping, but it can be used in other projects for other purposes too.
You can install the Annotation component with composer:
$ composer require doctrine/annotations
An annotation class is a representation of the later used annotation configuration in classes. The annotation class of the previous example looks like this:
The annotation class is declared as an annotation by
The access to the annotations happens by reflection of the class
containing them. There are multiple reader-classes implementing the
Doctrine\Common\Annotations\Reader interface, that can access the
annotations of a class. A common one is
1 use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationRegistry; // Deprecated and will be removed in 2.0 but currently needed AnnotationRegistry::registerLoader('class_exists'); $reflectionClass = new ReflectionClass(Foo::class); $property = $reflectionClass->getProperty('bar'); $reader = new AnnotationReader(); $myAnnotation = $reader->getPropertyAnnotation($property, MyAnnotation::class); echo $myAnnotation->myProperty; // result: "value" 2 3 4 5 6 7 8 9 10 11 12 13
AnnotationRegistry::registerLoader('class_exists') only works
if you already have an autoloader configured (i.e. composer autoloader).
Otherwise, please take a look to the other annotation autoload mechanisms.
A reader has multiple methods to access the annotations of a class.