2017-02-28 22 views
1

我有一個模型,它使用JMS序列化器對其屬性進行註釋。 在另一個使用此對象的類中,我想訪問註釋中的信息。 例子:訪問由註釋定義的對象屬性的序列化名稱

class ExampleObject 
{ 
    /** 
    * @var int The status code of a report 
    * 
    * @JMS\Expose 
    * @JMS\Type("integer") 
    * @JMS\SerializedName("StatusCode") 
    * @Accessor(getter="getStatusCode") 
    */ 
    public $statusCode; 

} 

正如你所看到的屬性是首字母大寫的風格,這是確定我們的編碼標準命名。但爲了將此對象中的信息傳遞給外部服務,我需要SerializedName。

所以我的想法是在這個類中編寫一個方法,該方法爲每個屬性提供了從註釋返回的SerializedName。是否可以通過方法訪問註釋中的信息?如果是的話如何?

我的想法是這樣的:

public function getSerializerName($propertyName) 
{ 
    $this->$propertyName; 
    // Do some magic here with the annotation info 
    return $serializedName; 
} 

所以「神奇」的部分是,我需要一些幫助。

回答

0

我發現那裏的神奇正在發生的事情: 在類的頭,你必須添加以下使用語句:

use Doctrine\Common\Annotations\AnnotationReader; 
use Doctrine\Common\Annotations\DocParser; 

得到SerializedName工作的方法如下:

/** 
* Returns the name from the Annotations used by the serializer. 
* 
* @param $propertyName property whose Annotation is requested 
* 
* @return mixed 
*/ 
public function getSerializerName($propertyName) 
{ 
    $reader = new AnnotationReader((new DocParser())); 
    $reflection = new \ReflectionProperty($this, $propertyName); 
    $serializedName = $reader->getPropertyAnnotation($reflection, 'JMS\Serializer\Annotation\SerializedName'); 

    return $serializedName->name; 
} 

現在,您可以從另一個類調用該名稱,該名稱用於序列化並使用它來處理任何您需要的名稱。

相關問題