Symfony 序列化程序 - 设置循环引用全局 [英] Symfony serializer - set circular reference global

查看:53
本文介绍了Symfony 序列化程序 - 设置循环引用全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Symfony(不是 JMSSerializer)的序列化器组件中使用任何配置或类似的东西设置循环引用限制?

Is there any way to set the circular reference limit in the serializer component of Symfony (not JMSSerializer) with any config or something like that?

我有一个带有 FOSRestBundle 的 REST 应用程序和一些包含其他实体的实体,这些实体也应该被序列化.但是我遇到了循环引用错误.

I have a REST Application with FOSRestBundle and some Entities that contain other entities which should be serialized too. But I'm running into circular reference errors.

我知道如何设置它:

$encoder    = new JsonEncoder();
$normalizer = new ObjectNormalizer();

$normalizer->setCircularReferenceHandler(function ($object) {
     return $object->getName();
});

但这必须在多个控制器中完成(对我来说是开销).我想在配置(.yml)中全局设置它,例如像这样:

But this has to be done in more than one controller (overhead for me). I want to set it globally in the config (.yml) e.g. like this:

framework: 
    serializer:
        enabled: true
        circular_limit: 5

没有找到与此相关的序列化程序 API 参考,所以我想知道这可能吗?

Found no serializer API reference for this so I wonder is it possible or not?

推荐答案

我发现的唯一方法是创建您自己的对象规范器以添加循环引用处理程序.

The only way I've found is to create your own object normalizer to add the circular reference handler.

最低限度的工作可以是:

A minimal working one can be:

<?php

namespace AppBundle\Serializer\Normalizer;

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

class AppObjectNormalizer extends ObjectNormalizer
{
    public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null)
    {
        parent::__construct($classMetadataFactory, $nameConverter, $propertyAccessor, $propertyTypeExtractor);

        $this->setCircularReferenceHandler(function ($object) {
            return $object->getName();
        });
    }
}

然后声明为优先级比默认服务(-1000)略高的服务:

Then declare as a service with a slithly higher priority than the default one (which is -1000):

<service
    id="app.serializer.normalizer.object"
    class="AppBundle\Serializer\Normalizer\AppObjectNormalizer"
    public="false"
    parent="serializer.normalizer.object">

    <tag name="serializer.normalizer" priority="-500" />
</service>

默认情况下,此规范化器将在您项目的任何地方使用.

This normalizer will be used by default everywhere in your project.

这篇关于Symfony 序列化程序 - 设置循环引用全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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