koosa
koosa

Reputation: 3040

Using Doctrine 2 Annotation reader for customized annotations

I'm pretty new to Doctrine 2 and am using annotations to do my database mapping. I want to take things a little bit further and use some custom annotations. The aim is to be able to make forms and such that can have settings created through annotations. I'm having trouble reading ANY annotations - even class ones such as @Table aren't being returned from the parser.

I am using Codeigniter 2 and Modular Extensions. In my controller I have:

$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$reader->setDefaultAnnotationNamespace('MyCompany\Annotations');
$reflClass = new ReflectionClass('models\User');
$classAnnotations = $reader->getClassAnnotations($reflClass);
print_r($classAnnotations);

Which returns an empty array.

I then have a file in my libraries/annotations folder, Bar.php:

namespace MyCompany\Annotations;

class Bar extends \Doctrine\Common\Annotations\Annotation
{
    public $foo;
}

and lastly, my user model:

/**
* @Entity
* @Table(name="user")
* @MyCompany\Annotations\Bar(foo="bar")
* @MyCompany\Annotations\Foo(bar="foo")
*/

class User {

}

I am trying to follow this example: http://www.doctrine-project.org/projects/common/2.0/docs/reference/annotations/en#setup-and-configuration

Thanks for your help in advance!

Mark.

Upvotes: 3

Views: 5112

Answers (2)

Faizal Pribadi
Faizal Pribadi

Reputation: 31

use

Doctrine\Common\Annotations\AnnotationRegistry

AnnotationRegistry::RegisterLoader($universalClassLoader);
AnnotationRegistry::RegisterFile(__DIR__ . ' PATH_TO_DoctrineAnnotations.php ');

Upvotes: 3

jmlnik
jmlnik

Reputation: 2887

As you've figured out, you need to include your custom annotation files/classes before you can use them.

Though including them in your controller would work, why not do it the Doctrine way!

Doctrine2's ORM has a file called DoctrineAnnotations.php in the Doctrine/ORM/Mapping/Driver/ folder. It looks like this:

...
require_once __DIR__.'/../GeneratedValue.php';
require_once __DIR__.'/../Version.php';
require_once __DIR__.'/../JoinColumn.php';
require_once __DIR__.'/../JoinColumns.php';
require_once __DIR__.'/../Column.php';
...

So, what I've done is created a similar file in my library and load my annotations by including this "driver" (eg. in your bootstrap).

In my ZF-based app (using Guilherme Blanco's fabulous Zf1-D2 set-up), I just added my "annotations driver" to my application.ini, like this (all on one line):

resources.doctrine.orm.entityManagers.default
  .metadataDrivers.annotationRegistry.annotationFiles[]
  = APPLICATION_PATH "/path/to/my/library/ORM/Mapping/Driver/MyAnnotations.php"

Upvotes: 0

Related Questions