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.
<?php
namespace Project/Model;
class IndexedStuff
{
public $name;
public $value;
public $rawData;
}
Now create the handler
<?php
namespace Project/Serializer;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\Context;
class MyHandler implements SubscribingHandlerInterface
{
public function setEntityManager(Registry $registry) {
// Inject registry instead of entity manager to avoid circular dependency
$this->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