How to create a good hypermedia format using JMSSerializerBundle?

Suppose I want to create an XML response that looks something like this:

<?xml version="1.0" encoding="utf‐8"?> <product xmlns="urn:com.acme.prods" xmlns:atom="http://www.w3.org/2005/xlink"> <id>1234</id> <name>Red Stapler</name> <price currency="EUR">3.14</price> <atom:link rel="payment" type="application/com.acme.shop+xml" href="http://acme.com/products/1234/payment" /> </product> 

For a domain model that looks something like this:

 <?php // Product.php namespace Acme\Bundle\ProductBundle\Entity; use Acme\Bundle\ProductBundle\Money\Money; class Product { /** * @var integer */ private $id; /** * @var string */ private $name; /** * @var Money */ private $price; [..] } 

And the money class line by line:

 <?php // Money.php namespace Acme\Bundle\ProductBundle\Money; class Money { /** * @var string */ private $currency; /** * */ private $amount; } 

Now, to my questions. It would be quite simple to create an answer that looks like this

 <?xml version="1.0" encoding="utf‐8"?> <product> <id>1234</id> <name>Red Stapler</name> <price currency="EUR">3.14</price> </product> 

using annotations, XML, or YAML to tell the JMSSerializerBundle how to serialize the Product object. However, the xmlns:atom and <atom:link> entries should not be specified by the entity, since it should not have a clue as to where . You could also provide more links with various rel attributes, such as edit .
One solution that comes to mind will be a service that listens for serialization events for specific objects and adds these attributes and tags as needed. A service can use DI to receive a Request , Router service, etc., to generate these links in a format that is suitable for the requested format. IE in the XML response, it can set the corresponding type application/media-format+xml , whereas in json-response it can generate something like

 "links": [ { "rel": "payment", "type": "application/media-format+json", "href": "[...]" } ] 

Now, in the documentation for the JMSSerializerBundle , I find annotations for @PreSerialize and @PostSerialize , but they seem to only be able to call methods on the serialized object.
Does anyone know how to do this? Or do I need to use a template engine such as Twig and manually create an XML response?

+48
hateoas symfony hypermedia jmsserializerbundle
Sep 13 '12 at 13:15
source share
1 answer

For this situation, one Serializer package may not be enough, since it concerns only serialization and deserialization, and not more complex semantic tasks.

I would suggest looking at the FSCHateoasBundle to implement a fairly flexible format for your API.

+3
Nov 25
source share



All Articles