JMSSerializerBundle: specify a group for each attribute

I am using Symfony2 and JMSSerializerBundle to create an API. The system that JMSSerializer provides for setting various ways to serialize objects using groups is very useful, however, I don’t have enough way to specify which group you want to serialize in each parameter. Example:

I have an article related to the user (author). Articles as well as users can be serialized as a “list” or “details”, however I want users to be serialized sequentially as a “list” so that they are retrieved from the article (since the group “details” is reserved for use to retrieve the user and user only). The problem is that if I set the serializer as "details", then the author is also serialized as "details".

In my opinion, the code should look something like this:

/** * @var SCA\APIBundle\Entity\User * @Groups({"list" => "list", "details" => "list"}) */ private $author; 

where the array key indicates the way the parent element is serialized, and the value indicates the way that it should be serialized.

Any clue how can I achieve this?

+1
php symfony jmsserializerbundle
Dec 02
source share
1 answer

This should not be done on the arranged object, but on the composition.

In your case, I suppose you have something like this:

 class Article { /** * @var User * @Groups({"list", "details"}) */ private $author; } class User { private $firstName; private $lastName; } 

So, if you want to set the firstName property when serializing the linked object, you need to define the same group in the User object.

This will:

 class Article { /** * @var User * @Groups({"list", "details"}) */ private $author; } class User { /* * @Groups({"list"}) */ private $firstName; private $lastName; } 

If you need more control, you can define more explicit groups such as "article list", "username", "minimal user list", etc.

It is up to you to choose the best strategy for adoption.

0
Dec 12 '12 at 11:13
source share



All Articles