JMS_Serializer服务在Symfony2中不起作用 - 错误:允许的内存大小

时间:2014-05-20 00:29:15

标签: json symfony doctrine jmsserializerbundle

在我的Symfony2控制器中,我正在检索博客帖子作为教义实体的集合:

$posts = $this->getDoctrine()
        ->getRepository('MyBundle:Post')
        ->findPostDatesAscending();

我尽职尽责地安装了JMSSerializer软件包,因为它应该与Doctrine ORM一起使用,并且也在我的控制器中调用该服务:

$serializer = $this->container->get('jms_serializer'); 
$jsonContent = $serializer->serialize($posts, 'json');
echo $jsonContent;

但是,我收到以下错误:

  

FatalErrorException:错误:在C:\ wamp \ www \ Symfony \ vendor \ jms \ serializer \ src \ JMS \ Serializer \ GenericSerializationVisitor.php第58行中,允许的内存大小为134217728字节耗尽(尝试分配55204字节)

我已经尝试找到这个问题,并且似乎没有太多的乐趣将实体序列化为JSON工作。我确定这是某种递归问题,但我对Symfony2很新,所以我不确定为什么会这样,特别是我如何将这些实体/对象变成JSON字符串。

我差点忘了,我的帖子对象有一个同一个关系。不确定这是否相关:

/BlogBundle/Resources/config/doctrine/Blog.orm.yml
MyBundle\BlogBundle\Entity\Blog:
type: entity
repositoryClass: MyBundle\BlogBundle\Entity\BlogRepository
oneToMany:
    posts:
        targetEntity: Post
        mappedBy: blog
table: null
fields:
    id:
        type: integer
        id: true
        generator:
            strategy: AUTO
    blog:
        type: string
        length: '255'
uniqueConstraints:
    search_idx:
        columns: blog
lifecycleCallbacks: {  }

我的博客对象也映射到作者对象 - 真正的博客设置......

编辑:为了回应@kix,我在我的所有实体类中添加了排除代码(Post,请参阅下面的示例代码,博客和作者),它排除了所有要序列化的对象,并且STILL得到了内存错误。我将响应仅限于一篇博文,该帖只链接到博客(id和名称)和作者(id和名称)。

namespace MyBundle\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;

/**
 * The following annotations tells the serializer to skip all properties which
 * have not marked with @Expose.
 *
 * @ExclusionPolicy("all")
 */

/**
 * Post
 */
class Post
{
     /**
      * @var integer
      */
      private $id;
      ...etc

任何帮助将不胜感激,谢谢。

3 个答案:

答案 0 :(得分:0)

您应该尝试使用JMS Serializer' exclusion strategies来指定应该序列化哪些属性,哪些属性不应该序列化。

我认为你的对象有一些嵌套属性,这使得序列化过于复杂(可能它会获取帖子的博客,然后尝试序列化这个博客的其他帖子,等等)。

答案 1 :(得分:0)

如果你只是:

会发生什么
    $posts = $this->getDoctrine()->getRepository('MyBundle:Post')->findPostDatesAscending();
    return array('posts' => $posts);

试图发表评论,但没有声誉。

答案 2 :(得分:0)

在你的知识库中,只在所需的那些上创建select语句。包括外键,关系字段。一个工作实例

public function getAllVotersDesc()
{
    //return $this->findBy(array(), array('id' => 'DESC'));
    return $this
        ->createQueryBuilder('v')
        ->select('v.firstname','lastname')
       // ->where('v.dateCreated <= :now')->setParameter('now', new \DateTime())
        ->orderBy('v.dateCreated', 'DESC')
       // ->setMaxResults(10)
        ->getQuery()
        ->getResult()
    ;
}