symfony - JMS 序列化器 : How to limit the depth of serialisation for an object graph

标签 symfony jmsserializerbundle

也许这只是我对此注释的误解,但它并没有按预期工作。

我有以下对象图

User
 -> Company
  -> Users
   -> Groups
    -> Permissions

正如你所看到的,会有一些递归。 JMS 很好地处理了这个问题,它不序列化其他用户的公司属性以及当前用户的属性。

但是我希望连载停止并包括公司。

我尝试过这个,期望一旦级别 $context->level = 2 它就会停止

<?php
namespace FinalConcept\TimeTracker\EntitiesBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
 * FinalConcept\TimeTracker\EntitiesBundle\Entity
 *
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="FinalConcept\TimeTracker\EntitiesBundle\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
     /**
     * @ORM\ManyToOne(targetEntity="company", inversedBy="users")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
     * @JMS\MaxDepth(depth=1)
     */
    private $company;
}

然而事实并非如此。即使单步执行代码也没有说明如何阻止这种情况。

如果我只能为特定路径(即 User.Company)调用它,我很乐意创建自定义处理程序

我还需要这个用于具有以下图表的 User.Groups

User
 -> Groups
  -> Permissions
 -> Users
   -> Groups
     -> users ....

预先感谢您提供有关如何限制对象图序列化深度的任何帮助

最佳答案

因为我无法访问最新版本的序列化器,所以我必须找到 @MaxDepth 的解决方法。这也可能对您有帮助。

对所有连接的实体使用 @JMS\ExclusionPolicy("all")。

现在仅对那些您想要序列化的属性使用@JMS\Expose。 对于连接关系,仅在一个方向上使用此注释。这将解决您的问题。

namespace FinalConcept\TimeTracker\EntitiesBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
 * FinalConcept\TimeTracker\EntitiesBundle\Entity
 *
 * @JMS\ExclusionPolicy("all")
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="FinalConcept\TimeTracker\EntitiesBundle\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
     /**
     * @JMS\Expose
     * @ORM\ManyToOne(targetEntity="company", inversedBy="users")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
     */
    private $company;
}

关于symfony - JMS 序列化器 : How to limit the depth of serialisation for an object graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22590073/

相关文章:

symfony - Api 平台所需的过滤器

mysql - 如何在 Doctrine2 中获取与其他实体相关的 2 个实体

php - Symfony : eating all my ram when fetching from postgresql

php - symfony 4 api 突然变得非常慢

symfony - 如何让 JMS Serializer 在反序列化 JSON 而不是强制类型时抛出异常?

symfony - 在 Symfony2 中运行 PHPUnit 测试时,JMS Serializer 不读取配置

symfony - FOSRestBundle/JMSSerializerBundle : interact with Symfony2 Security roles

symfony - 如何从@Groups 包含策略 JMS Serializer 反序列化实体更新 symfony/doctrine 实体

Symfony cmf 生成 :bundle option

php - socket_create_listen 不适用于 Windows 中的所有接口(interface)