mattalxndr
mattalxndr

Reputation: 9418

When using Doctrine 2 custom annotations, what's the best way to get an array of all entity classes that have a specific annotation?

I'm reading this documentation article about Custom Annotations in Doctrine. I understand that I can use $reader->getClassAnnotations($reflClass) to retrieve the annotations on a particular class. What's the best way to get a list of all entity classes that have a specific annotation?

Upvotes: 1

Views: 2269

Answers (1)

wyxknouth
wyxknouth

Reputation: 36

$driver = new \Doctrine\ORM\Mapping\Driver\PHPDriver($entities_path );

$classes = $driver->getAllClassNames();

foreach ($classes as $key => $class) {     

      $reader = new \Doctrine\Common\Annotations\AnnotationReader();

      $annotationReader = new \Doctrine\Common\Annotations\CachedReader(
                                              $reader, 
                                              new \Doctrine\Common\Cache\ArrayCache()
                                           );

      $reflClass = new ReflectionClass("\Entities\\".$reportableClass);
      $annotation = $annotationReader->getClassAnnotation(
                                                     $reflClass, 
                                                     'Custom_Annotation'
                                                  );
      if (is_null($annotation)) {
          unset($classes[$key]);
      }
}

The AbstractFileDriver(Doctrine\ORM\Mapping\Driver\AbstractFileDriver.php) documentation of Doctrine said:

Base driver for file-based metadata drivers.

A file driver operates in a mode where it loads the mapping files of individual classes on demand. This requires the user to adhere to the convention of 1 mapping file per class and the file names of the mapping files must correspond to the full class name, including namespace, with the namespace delimiters '\', replaced by dots '.'.

Also you could use instead of the PhpDriver, the DatabaseDriver (Doctrine\ORM\Mapping\Driver\DatabaseDriver.php).

Upvotes: 2

Related Questions