Symfony2 custom annotations for objects

Does anyone know if it is possible that with the help of the annotation reader new user annotations for objects without Doctrine can be read? All that I have seen so far is either a controller, or in some way expand the doctrine.

What I would like to do is something like this:

class MyTestClass {

  /**
   * @MyBundleName\Foo
   */
  public $foo_var;

  /** 
   * @MyBundleName\Bar
   */
  public $bar_var;
}

And then you have code that, when specifying the instance, MyTestClasscan decide which annotation is applied to which attribute.

+5
source share
1 answer

Right, get a little deeper into how the Doctrine does it, and I think I know how to do it. Therefore, if someone else needs to do it here, how I do it (we will be grateful for any feedback)

, , config.yml annotation_reader, .

, Doctrine, , Foo , - :

namespace MyBundleName

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

}

, :

$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
}

, - !

+10

All Articles