2017-05-15 56 views
0

我使用Symfony 3,Doctrine 2,FOS Rest束和JMS串行器。 我在應用程序中使用排除所有策略,然後選擇性地暴露字段。Jms串行器動態曝光

在用戶實體上,我希望能夠爲當前用戶公開其他字段。

例如對於正常的api/user/{id}端點,我想公開正常的數據,但對於api/user/current我想公開稍微多一點的數據。

例如,

/** 
* ... 
* @Serializer\ExclusionPolicy("all") 
*/ 
class Users implements UserInterface 
{ 
    /** 
    * @var string 
    * @Serializer\Expose 
    * 
    * @ORM\Column(name="name", type="string", length=255, nullable=true) 
    */ 
    private $name; 


    /** 
    * @var string 
    * 
    * @ORM\Column(name="secretfield", type="string", length=255, nullable=true) 
    */ 
    private $secretfield; 

我曾嘗試@groups裝飾,但是這隻能進一步削減的領域,需要我不斷變化的負載,並小心翼翼地到處設置「默認」組上下文。

我看過Dynamic Exclusion Strategy,在the docs中提到,但我無法弄清楚它是否是我需要或不需要的,以及哪些變量可用於構建表達式。

任何想法什麼是最好的辦法做到這一點?

回答

1

我主要擔心的是「將所有內容默認發送」行爲,這可能來自將排除策略設置爲無。

但我仔細查看了這些組,並發現我可以在配置中設置一個默認組。

fos_rest: 
    serializer: 
    groups: ["default"] 

我測試了這個我的用戶控制器上,並沒有對實體或串行背景指定任何團體,它返回什麼。 所以我修改我的實體使用@Serializer\Groups({"default"})而不是@Serializer\Expose。這使我回到了與我開始時相同的返回數據。

然後,我將current_user組添加到實體的祕密字段中,並將該組添加到序列化程序上下文中以獲取該特定視圖的這些附加字段。

在實體:

/** 
* ... 
* @Serializer\ExclusionPolicy("none") 
*/ 
class Users implements UserInterface 
{ 
    /** 
    * @var string 
    * @Serializer\Groups({"default"}) 
    * 
    * @ORM\Column(name="name", type="string", length=255, nullable=true) 
    */ 
    private $name; 


    /** 
    * @var string 
    * @Serializer\Groups({"current_user"}) 
    * 
    * @ORM\Column(name="secretfield", type="string", length=255, nullable=true) 
    */ 
    private $secretfield; 

和Controller:

/** 
* @Rest\Get("user/current") 
* 
* @return \FOS\RestBundle\View\View 
*/ 
public function getCurrentAction() 
{ 
    $me = $this->getUser(); 

    $view = new View($me, Response::HTTP_OK); 
    /** @var Context $context */ 
    $context = $view->getContext(); 
    $context->setGroups(['current_user', 'default']); 
    $view->setContext($context); 

    return $view; 
} 
+0

如果設置一個全局組這樣的,那麼你就可以指定該組中的每一個實體類,並在每你想要顯示的屬性,所以它不理想。使用公開,你可以讓某些實體默認沒有公開,並指定要公開的實體,但其他文件可能只公開所有實體。但是通過這種方法,你不得不註釋一個你只想返回所有實體的每個屬性。 – Jayd