这个怎么样:http: //jmsyst.com/libs/serializer/master/handlers
总之,您定义了一个接收对象并返回文本或数组(将转换为 json)的类。
您的“IndexedStuff”类包含一个奇怪的计算字段,由于某种原因应该在序列化时计算。
<?php
namespace Project/Model;
class IndexedStuff
{
public $name;
public $value;
public $rawData;
}
现在创建处理程序
<?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
}
}
最后注册服务
services:
project.serializer.stuff:
class: Project\Serializer\MyHandler
calls:
- [setEntityManager, ["@doctrine"]]
现在,无论你想序列化“IndexedStuff”类型的对象,你都会得到一个像这样的 json
{"name": "myName", "score" => 0.3432}
通过这种方式,您可以完全自定义实体的序列化方式