I have to serialize an object and I get the ever so common "circular reference error"
I have used the old Symfony method :
$normalizer = new ObjectNormalizer();
// Add Circular reference handler
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$normalizers = array($normalizer);
$encoders = [new JsonEncoder()];
$serializer = new Serializer($normalizers, $encoders);
This work but as of Symfony 4.2 I get the exception you see in the title of this question :
use the "circular_reference_handler" key of the context instead Symfony 4.2
I cannot find any reference to this in the Symfony documentation concerning the Serializer.
https://symfony.com/doc/current/components/serializer.html#handling-circular-references
Does any one know how to use this "key of context" instead of the old method?
Unfortunately it is a bit hidden away in the docs, but you can create a class instead of using an anonymous function and then configure the serializer to use this service by default.
It is part of the configuration reference: https://symfony.com/doc/current/reference/configuration/framework.html#circular-reference-handler
# config/packages/serializer.yaml
serializer:
circular_reference_handler: 'App\Serializer\MyCircularReferenceHandler'
There is no interface specified. Instead the class needs to be invokable. So in your case it could look like this:
class MyCircularReferenceHandler
{
public function __invoke($object)
{
return $object->id;
}
}