Search code examples
symfonyserializationdoctrine-ormdoctrinesymfony4

Fix circular reference in symfony when using SerializerInterface


I'm getting a circular reference error when serializing a component. Usually this can be fixed using

$normalizer->setCircularReferenceHandler()

However, I'm using the SerializerInterface like this:

/**
  * @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')))
   );
  }

Is it possible to fix a circular reference error when serializing using this interface?


Solution

  • You totally can. Just add this in your framework config.

    framework:
        serializer:
            circular_reference_handler: App\Serializer\MyCustomCircularReferenceHandler
    

    This handler will work globally. Make sure you register it as a service. I does not need to implement any interface. So just a class with an __invoke() will suffice. That invoke will receive the object that is being "circle referenced" as the only argument.

    You can either return the id or do some really cool stuff, like creating a uri for the resource. But the implementation details are totally up to you, as long as you don't return the same object, everything will be fine.

    :)