使用“circular_reference_handler"上下文的键而不是 symfony 4.2 [英] Use the "circular_reference_handler" key of the context instead symfony 4.2

查看:59
本文介绍了使用“circular_reference_handler"上下文的键而不是 symfony 4.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须序列化一个对象,但我得到了非常常见的循环引用错误"

I have to serialize an object and I get the ever so common "circular reference error"

我使用了旧的 Symfony 方法:

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);

这项工作但从 Symfony 4.2 开始,我得到了您在此问题标题中看到的异常:

This work but as of Symfony 4.2 I get the exception you see in the title of this question :

使用上下文的circular_reference_handler"键代替Symfony 4.2

use the "circular_reference_handler" key of the context instead Symfony 4.2

我在有关序列化程序的 Symfony 文档中找不到任何对此的引用.

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.

它是配置参考的一部分:https://symfony.com/doc/current/reference/configuration/framework.html#reference-serializer-circular-reference-handler

It is part of the configuration reference: https://symfony.com/doc/current/reference/configuration/framework.html#reference-serializer-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;
    }
}

这篇关于使用“circular_reference_handler"上下文的键而不是 symfony 4.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆