2012-04-06 6 views
5

번들이 Annotation Reader를 사용하여 Doctrine 이외의 객체에 대한 새로운 커스터마이징 주석을 읽는 것이 가능한지 아는 사람 있습니까? 지금까지 내가 본 모든 것은 컨트롤러에 대한 것이거나 교리를 어떤 식 으로든 확장하는 것입니다. 내가 할 수 있도록하고 싶습니다 무엇Symfony2 객체에 대한 커스텀 주석

이 같은 것입니다 :

class MyTestClass { 

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

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

그리고 주어 졌을 때 MyTestClass의 인스턴스가 주석이있는 속성에 적용되는 해결할 수있는 몇 가지 코드가 있습니다.

답변

10

오른쪽, Doctrine이 이것을 어떻게하는지 파고 들며, 나는 그것을 어떻게하는지 안다. 그래서 누군가 다른 사람이 이것을 할 필요가 있다면 여기에 내가 어떻게하는지 (어떤 의견이라도 감사 할 것이다)

나는 주석을 읽는 데 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 
} 

다른 사람에게 유용 할 수있는 희망!