This project is not being actively maintained. If you are interested in helping to maintain this project, take a look at the open issues on GitHub and submit pull requests.

Getting Started

Deprecation notice

PHP 8 introduced attributes, which are a native replacement for annotations. As such, this library is considered feature complete, and should receive exclusively bugfixes and security fixes.

We do not recommend using this library in new projects and encourage authors of downstream libraries to offer support for attributes as an alternative to Doctrine Annotations.

Have a look at our blog to learn more.

Introduction

Doctrine Annotations allows to implement custom annotation functionality for PHP classes and functions.

1class Foo { /** * @MyAnnotation(myProperty="value") */ private $bar; }
2
3
4
5
6
7

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 @ char.

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.

Installation

You can install the Annotation component with composer:

$ composer require doctrine/annotations

Create an annotation class

An annotation class is a representation of the later used annotation configuration in classes. The annotation class of the previous example looks like this:

1/** * @Annotation */ final class MyAnnotation { public $myProperty; }
2
3
4
5
6
7

The annotation class is declared as an annotation by @Annotation.

Read more about custom annotations.

Reading annotations

The access to the annotations happens by reflection of the class or function 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 Doctrine\Common\Annotations\AnnotationReader:

1use Doctrine\Common\Annotations\AnnotationReader; $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

A reader has multiple methods to access the annotations of a class or function.

Read more about handling annotations.

IDE Support

Some IDEs already provide support for annotations: