Symfony2对象的自定义注释

pog*_*ogo 5 symfony

有没有人知道是否可以让一个包使用注释阅读器来读取非Doctrine对象的新自定义注释?到目前为止,我所看到的一切都是为了控制器或以某种方式扩展Doctrine.

我希望能做的是这样的:

class MyTestClass {

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

  /** 
   * @MyBundleName\Bar
   */
  public $bar_var;
}
Run Code Online (Sandbox Code Playgroud)

然后有一些代码,当给定一个实例时MyTestClass可以解决哪个注释应用于哪个属性.

pog*_*ogo 10

对,更多地深入研究Doctrine如何做到这一点,我想我知道该怎么做.所以,如果其他人需要这样做,我就是这样做的(会感激任何反馈)

我有一个服务,我用来读取注释,所以在config.yml我已经包含了annotation_reader提供访问读取注释的方法的服务.

每个注释都需要解析为一个类,并且该类必须扩展基本的Doctrine注释类,所以要从我的问题中执行Foo注释,你会做类似的事情:

namespace MyBundleName

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

}
Run Code Online (Sandbox Code Playgroud)

然后您可以通过执行以下操作来阅读注释:

$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
}
Run Code Online (Sandbox Code Playgroud)

希望对别人有用!