2012-04-06 63 views
5

有谁知道是否有可能使用注释阅读器读取非Doctrine对象的新自定义注释?到目前为止,我所看到的一切都是为了控制者或者以某种方式扩展主义。Symfony2对象的自定义注释

我想什么,能够做的就是这样的事情:

class MyTestClass { 

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

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

然后有一些代码,当给出的MyTestClass一个实例可以运行哪些应用到属性的注释。

回答

10

没错,有点更深入的研究主张如何做到这一点,我想我知道该怎么做。所以如果有人需要这样做,这里是我怎么做的(将欣赏任何反馈)

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

每个注释需要解决的一类和类必须扩展基本教义注解类,这样做从我的问题美孚注解你会做这样的事情:

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 
} 

希望能对其他人有用!