I\'ve an entity I usually serialize using the JMS Serializer bundle. I have to add to the serialization some fields that doesn\'t reside in the entity itself but are gathere
What about this: http://jmsyst.com/libs/serializer/master/handlers
In summary, you define a class that receives an object and returns text or an array (that will be converted to json).
You have class "IndexedStuff" that contains a weird calculated field that for some reason should be calculated at serialization time.
Now create the handler
em = $registry->getEntityManager();
}
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'Project/Model/IndexedStuff',
'method' => 'serializeIndexedStuffToJson',
),
);
}
public function serializeIndexedStuffToJson(JsonSerializationVisitor $visitor, Project/Model/IndexedStuff $stuff, array $type, Context $context)
{
// Build your object here and return it
$score = $this->em->find("ProjectBundle:Calculator", $stuff->value)
return array("score" => $score->getIndexScore(), "name"=> $score->name
}
}
Finally register the service
services:
project.serializer.stuff:
class: Project\Serializer\MyHandler
calls:
- [setEntityManager, ["@doctrine"]]
Now everywhere you want to serialize an object of type "IndexedStuff" you will get a json like this
{"name": "myName", "score" => 0.3432}
By this way you can fully customize how your entity is serialized