【问题标题】:Symfony2 doctrine and responseSymfony2 原则和响应
【发布时间】:2014-08-16 08:12:35
【问题描述】:

我有一个小问题,我正在尝试发送一个 json 响应,但我得到的只是一个空对象。

这是我的代码:

//Get the data from DB
$template = $this->getDoctrine()
    ->getRepository('EVRYgroBundle:Template')
    ->findOneBy(
        array('active' => 1)
        );

    if (!$template) {
        throw $this->createNotFoundException(
            'No product found for id '
        );
    }

  //Send the response
 $response = new Response();
 $response->setContent(json_encode($template));
 return $response;

当我查看它时,它显示的只是 {} 我也尝试过使用 jsonResponse 和这段代码:

$response = new JsonResponse();
$response->setData($template);

而且我不知道我做错了什么!

【问题讨论】:

    标签: json symfony doctrine


    【解决方案1】:

    json_encode 需要一个数组作为第一个参数。当你用一个对象调用它时,可能会显示公共属性。为了保护属性(应该如此),您可以向您的实体添加公开函数:

    /**
     * delivers all properties and values of the entity easily
     *
     * @return array
     */
    public function expose()
    {
        return get_object_vars($this);
    }
    

    然后调用

    $response->setData(json_encode($template->expose()));
    

    这样你就可以保持你的实体干净,只能通过 getter 和 setter 方法访问,你仍然可以通过 json 访问所有属性。

    【讨论】:

      【解决方案2】:

      好吧,我发现了问题,问题在于保存数据库信息的一些变量被设置为受保护而不是公开。

      【讨论】:

      • 你没有所有的getter和setter吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 2015-07-24
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多