简体   繁体   English

自定义循环引用处理程序以进行序列化

[英]Custom circular reference handler for serialization

Trying to serialize an entity which causes some circular reference issues 尝试序列化实体会导致一些循环引用问题

class Comment
{
    /**
     * @var Discussion
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\Discussion", inversedBy="comments")
     * @ORM\JoinColumn(nullable=false)
     */
    private $discussion;
}

class Discussion
{
    /**
     * @var Comment[]|ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="discussion")
     */
    private $comments;
}

Since I'm using the Serializer component via injecting the SerializerInterface I tried to extend my framework.yaml with: 由于我通过注入SerializerInterface来使用Serializer组件,因此我尝试通过以下方式扩展我的framework.yaml

serializer:
    circular_reference_handler: App\Utils\CircularReferenceHandler

Where the handler class implements the __invoke method which simply returns the ID of the object: 处理程序类实现__invoke方法的地方,该方法仅返回对象的ID:

public function __invoke($object, string $format = null, array $context = [])
{
    if (method_exists($object, 'getId')) {
        return $object->getId();
    }
    return '';
}

Unfortunately this doesn't work and I'm resulting in an endless loop (exceeding available memory). 不幸的是,这行不通,并且导致了无限循环(超出可用内存)。 What am I doing wrong? 我究竟做错了什么?

If I understand correctly, you're trying to use the serializer and you're running into issues with the ManyToOne relationship causing a circular reference error. 如果我理解正确,那么您正在尝试使用序列化程序,并且遇到了ManyToOne关系的问题,从而导致循环引用错误。

I solved this in the past with: 我过去用以下方法解决了这个问题:

$normalizer->setignoredattributes()

This allows you to ignore ignore attributes of an object your trying to serialize. 这使您可以忽略尝试序列化的对象的忽略属性。 So this way you will only serialize the discussions reference down to comments, but not the comments objects reference back to discussion. 因此,通过这种方式,您只会将讨论参考序列化为评论,而不会将评论对象参考序列化回讨论。 You'll ignore the comments objects reference back to discussion. 您将忽略评论对象对讨论的引用。

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

$normalizer = new ObjectNormalizer();
$normalizer->setIgnoredAttributes(array('age'));
$encoder = new JsonEncoder();

$serializer = new Serializer(array($normalizer), array($encoder));
$serializer->serialize($person, 'json');

The key here being: 关键是:

$normalizer->setIgnoredAttributes(array('age')); 

That was simply the example from the documentation which you may read here: https://symfony.com/doc/current/components/serializer.html#ignoring-attributes 这只是文档中的示例,您可以在此处阅读: https : //symfony.com/doc/current/components/serializer.html#ignoring-attributes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM