Symfony2 - 实体 findAll return API 上的大量响应

Symfony2 - Entity findAll return large response on API

我有一个用 Symfony2 开发的 API,但是当我向它发送请求时,响应 returns 只有 40 行 204Mb...这是代码:

$em = $this->getDoctrine()->getManager();
$themes = $em->getRepository("KlickpagesAdminBundle:Theme")->findAll();
return $themes;

我使用 FOSRestBundle 进行序列化和 returns json。

我该如何解决这个问题?

Aa @Cerad 说这很像,因为与其他实体的关系和延迟加载循环

为了快速测试,请从序列化中排除所有字段,除了像这样的少数标量字段:

use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\ExclusionPolicy;

/**
 * Group
 *
 * @ExclusionPolicy("all")
 */
class Group implements GroupInterface
{
    /**
     * @Expose
     * @var integer
     */
    private $id;

    /**
     * @Expose
     * @var string
     */
    private $title;

    /**
     * Relation to privilegesis not explicitly exposed.
     * @var Privilege[]
     */
    private $privileges;

    /**
     * Relation to Users not explicitly exposed.

     * @var User[]
     */
    private $users;
    ...

重要的部分是 exclusionStrategy 和 expose antations。

如果这会有所帮助,您肯定会得到注释的循环序列化,正确的解决方案是定义序列化组,可以这样说:

     /**
     * @Expose
     * @Groups({"groupDetail", "userAuthenticate"})
     *
     * @var Privilege[]
     */
    private $privileges;

    /**
     * @Expose
     * @Groups({"groupDetail"})
     *
     * @var User[]|ArrayCollection
     */
    private $users;

然后您可以定义哪个组应该是在您的控制器上或以编程方式序列化的响应。

 // controllerAction

     /*
     * @Annotations\View(serializerGroups={"Default","groupDetail"})
     */
     public function getGroupAction($groupId) { ... }

// programatically

    ...
    /** @var $context SerializationContext */
    $context             = SerializationContext::create();
    $serializationGroups = ['Default', 'GroupDetail'];
    $context->setGroups($serializationGroups);
    $view = $this->view($collection, 200);
    $view->setSerializationContext($context);

    return $this->handleView($view);
    ...

资源:http://jmsyst.com/libs/serializer/master/cookbook/exclusion_strategies