在运行时配置JMSSerializer

时间:2014-05-21 07:46:06

标签: symfony doctrine-orm jmsserializerbundle

我有2个关联实体,VenuePromo(多对多)。

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
class Venue {
    ...

    /**
     * @ORM\ManyToMany(targetEntity="Promo", inversedBy="venues")
     * @ORM\JoinTable(name="promo_venues")
     * @JMS\Exclude()
     */
    private $promos;

    ...
}

class Promo{
    /**
     * @ORM\ManyToMany(targetEntity="Venue", mappedBy="promos")
     * @JMS\Exclude()
     */
    private $venues;
}

我正在编写一个RESTful API来输出这些表的数据。在一个动作中,我需要输出与促销相关联的venues(1)。在另一个方面,我需要输出venues的列表而不包含促销数据(2)。

要解决(1),我可以简单地在Promo::venues中远程排除注释。但是,这将导致在{2}中输出venues列表,这是不合需要的。

我查看了代码,发现JMS的Serializer并没有为其成员提供getter。

问题:有没有办法动态更新serialiser配置(在控制器内部),特别是添加/删除字段级配置?

1 个答案:

答案 0 :(得分:1)

使用Groups Exclusion Strategy

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

class Venue {
    ...

    /**
     * @ORM\ManyToMany(targetEntity="Promo", inversedBy="venues")
     * @ORM\JoinTable(name="promo_venues")
     */
     private $promos;

     ...
}

class Promo{
    /**
     * @ORM\ManyToMany(targetEntity="Promo", mappedBy="promos")
     * @JMS\Groups("onlyVenues")
     */
    private $venues;
}

在您的控制器中,您可以执行(2):

$serializer->serialize($entities, 'json', SerializationContext::create()->setGroups(array('onlyVenues')));

对于(1),序列化而不设置任何组(即不应用排除策略)。