使用 SerializerInterface 时修复 symfony 中的循环引用

Fix circular reference in symfony when using SerializerInterface

序列化组件时出现循环引用错误。通常这可以使用

修复
$normalizer->setCircularReferenceHandler()

但是,我使用的 SerializerInterface 是这样的:

/**
  * @Route("/get/{id}", name="get_order_by_id", methods="GET")
  */
 public function getOrderById(SerializerInterface $serializer, OrderRepository $orderRepository, $id): Response
 {
   return new Response($serializer->serialize(
     $orderRepository->find($id),
     'json',
     array('groups' => array('default')))
   );
  }

是否可以修复使用此接口进行序列化时的循环引用错误?

根据界面上的 Symfony API Reference,似乎没有办法执行该函数或检索规范化器。

即使在 Serializer 中,也没有在创建序列化程序后检索规范化程序的方法。

您最好在序列化程序之前创建规范化程序以实现此目的,而不是通过配置文件注入接口。 (Relevant docs link)

你完全可以。只需将其添加到您的框架配置中即可。

framework:
    serializer:
        circular_reference_handler: App\Serializer\MyCustomCircularReferenceHandler

此处理程序将在全球范围内工作。确保将其注册为服务。我不需要实现任何接口。所以只需 class 和 __invoke() 就足够了。该调用将接收 "circle referenced" 作为唯一参数的对象。

您可以 return id 或做一些非常酷的事情,比如为资源创建一个 uri。但实现细节完全取决于您,只要您不 return 同一个对象,一切都会好起来的。

:)