Doctrine Annotations Library post
Posted on 2010-08-02 by jwage
The Doctrine Annotations library was born from a need in the Doctrine2 ORM to allow the mapping information to be specified inside the doc-blocks of classes, properties and methods. The library is independent and can be used in your own libraries to implement doc block annotations.
Setup and Configuration
To use the annotations library is simple, you just need to create a new AnnotationReader
instance:
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
Usage
Using the library API is simple. Imagine you had some annotation classes that looked like the following:
namespace MyCompany\Annotations;
class Foo extends \Doctrine\Common\Annotations\Annotation
{
public $bar;
}
class Bar extends \Doctrine\Common\Annotations\Annotation
{
public $foo;
}
Now to use the annotations you would just need to do the following:
/**
* @MyCompany\Annotations\Foo(bar="test")
* @MyCompany\Annotations\Bar(foo="test")
*/
class User
{
}
Now we can write a script to get the annotations above:
$reflClass = new ReflectionClass('User');
$classAnnotations = $reader->getClassAnnotations($reflClass);
echo $classAnnotations['MyCompany\Annotations\Foo']->bar; // prints foo
echo $classAnnotations['MyCompany\Annotations\Foo']->foo; // prints bar
You have a complete API for retrieving annotation class instances from a class, property or method docblock:
- getClassAnnotations(ReflectionClass $class)
- getClassAnnotation(ReflectionClass $class, $annotation)
- getPropertyAnnotations(ReflectionProperty $property)
- getPropertyAnnotation(ReflectionProperty $property, $annotation)
- getMethodAnnotations(ReflectionMethod $method)
- getMethodAnnotation(ReflectionMethod $method, $annotation)
Read the full documentation to learn more about how to use the Doctrine annotations library!
Categories: articles