Symfony2 custom annotations for objects

symfony

Solution

Right, bit more digging into how Doctrine does this and I think I know how to do it. So if anyone else needs to do this here's how I'm doing it (would be appreciative of any feedback)

I have a service that I'm using to read the annotations so in config.yml I've included the `annotation_reader` service which provides access to the methods to read your annotations.

Each annotation needs to resolve to a class and the class must extend the base Doctrine annotation class, so to do the Foo annotation from my question you'd do something like:

namespace MyBundleName

class Foo extends \Doctrine\Common\Annotations\Annotation {

}

Then you can read the annotations by doing:

$class = get_class($object);
foreach(object_get_vars($object) as $fieldname => $val){

    //$this->annotationReader is an instance of the annotation_reader service
    $annotations = $this->annotationReader
                   ->getPropertyAnnotations(
                      new \ReflectionProperty($class, $fieldName)
                     );

   //$annotations will now contain an array of matched annotations, most likely just an instance of the annotation class created earlier
}

Hope that can be of use to someone else!

Problem

Does anyone know if it's possible to have a bundle use the annotation reader to read new custom annotations for non Doctrine objects? Everything I've seen so far is either for a controller or to extend Doctrine in some way. What I'd like to be able to do is something like this: ``` class MyTestClass { /** * @MyBundleName\Foo */ public $foo_var; /** * @MyBundleName\Bar */ public $bar_var; } ``` And then have some code that when given an instance of `MyTestClass` could work out which annotation applied to which attribute.

Original source