これは、上記の問題を解決するためにこれまでに思いついた最良の解決策です。JMSSerializer コードの変更は必要ありません。完全なコードはこの Gist にあります:
https://gist.github.com/Jaap-van-Hengstum/0d400ea4f986d8f8a044
秘訣は、空の「偽の」クラスを作成することです。
namespace MyApp\ApiBundle\Serializer;
class SerializerProxyType
{
// this class is supposed to be empty
}
customDoctrineProxySubscriber
で、イベント タイプをそのクラスに設定します。このように、JMSSerializer はそのタイプをアノテーション処理に使用するため、 のようなアノテーションに遭遇したときに Doctrine プロキシーをトリガーしません@VirtualProperty
。
class DoctrineProxySubscriber implements EventSubscriberInterface
{
public function onPreSerialize(PreSerializeEvent $event)
{
$object = $event->getObject();
$type = $event->getType();
...
// This line is commented, so proxy loading on serializing is disabled
// $object->__load();
if ( ! $virtualType) {
// This line is commented because a different type is used
// $event->setType(get_parent_class($object));
// This assumes that every Doctrine entity has a single 'Id' primary
// key field.
$event->setType('MyApp\ApiBundle\Serializer\SerializerProxyType',
["id" => $object->getId()]);
}
}
public static function getSubscribedEvents()
{
return array(
array('event' => 'serializer.pre_serialize', 'method' => 'onPreSerialize'),
);
}
}
その後、JMSSerializer ハンドラーを使用して、空のクラスのカスタム ハンドラーを追加できます。このハンドラーは、シリアライズされた json/xml にエンティティの ID を含めるだけです。
class DoctrineProxyHandler implements SubscribingHandlerInterface
{
/**
* {@inheritdoc}
*/
public static function getSubscribingMethods()
{
$methods = [];
foreach (array('json', 'xml') as $format)
{
$methods[] = [
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => $format,
'type' => 'MyApp\\ApiBundle\\Serializer\\SerializerProxyType',
'method' => 'serializeTo' . ucfirst($format),
];
}
return $methods;
}
public function serializeToJson(VisitorInterface $visitor, $entity, array $type, Context $context)
{
$object = new \stdClass();
$object->id = $type['params']['id'];
return $object;
}
public function serializeToXml(XmlSerializationVisitor $visitor, $entity, array $type, Context $context)
{
$visitor->getCurrentNode()->appendChild(
$node = $visitor->getDocument()->createElement('id', $type['params']['id'])
);
return $node;
}
}
これらのクラスを使用するように Symfony を構成するには:
parameters:
jms_serializer.doctrine_proxy_subscriber.class: MyApp\ApiBundle\Serializer\DoctrineProxySubscriber
services:
doctrineproxy_handler:
class: MyApp\ApiBundle\Serializer\DoctrineProxyHandler
tags:
- { name: jms_serializer.subscribing_handler }