symfony - 从动作中的对等方法调用返回JSON

时间:2011-03-24 16:01:19

标签: symfony1 propel

我有一些代码检查参数,并调用peer方法从DB获取项目。

我需要获得的是JSON中的这些项目。

我的对等方法如下:

public static function searchFromRequest($word)
{
    $c = new Criteria();
    $c->addJoin(self::ARTICLE_ID, ArticlePeer::ID);
    $c->add(self::TITLE, '%'.$word.'%', Criteria::LIKE);
    $c->addAnd(self::ARTICLE_ID, null, Criteria::ISNOTNULL);
    $c->addAscendingOrderByColumn(self::TITLE);
    return self::doSelect($c);
}

我的行动是:

public function executeSearch()
{
    $this->word = $this->getRequestParameter('word');
    $this->content_type = $this->getRequestParameter('content_type');
    if($this->content_type == 'article')
    {
        $words = ItemPeer::searchFromRequest($this->word);
    }
    else
    { 
       echo "Nothing here";
    }

我可以var_dump($words)我得到一个项目的数组(集合)。问题是,如何返回JSON中的所有项目?

我尝试过使用:

        $this->getResponse()->setHttpHeader('Content-type', 'application/json');
        $words = ItemPeer::searchFromArticleRequest($this->word);
        return $this->renderText(json_encode($words));

但这只返回空JSON括号的加载:[{},{},{},{},{},{},{},{},{},{},{},{},{},{}]

由于

4 个答案:

答案 0 :(得分:3)

似乎json_encode()不喜欢Propel Objects的构建方式。

另一种解决方案可能是使用XXXPeer::doSelectStmt()

强制Propel返回基本关联对象
public static function searchFromRequest($word, $returnPropelObjects = true)
{
    $c = new Criteria();
    $c->addJoin(self::ARTICLE_ID, ArticlePeer::ID);
    $c->add(self::TITLE, '%'.$word.'%', Criteria::LIKE);
    $c->addAnd(self::ARTICLE_ID, null, Criteria::ISNOTNULL);
    $c->addAscendingOrderByColumn(self::TITLE);

    if ($returnPropelObjects)
      return self::doSelect($c);

    $stmt = self::doSelectStmt($c);
    $results = array();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $results[] = $row;
    }
    return $results;
}

答案 1 :(得分:3)

Propel 1.6:

  • 对象 - >的toJSON();
  • 收藏 - > exportTo( 'JSON');

答案 2 :(得分:1)

json_encode / json_decode只能编码/解码PHP数组而不是对象。变量

$words

将是一个Item对象数组,这就是你写的输出的原因。

基本上有两种解决方案。您编写自己的json编码器,适用于对象,如此处的第一条注释:

http://php.net/manual/en/function.json-encode.php

或者您编写了一个将Item对象转换为PHP数组的函数,如下所示:

http://www.phpro.org/examples/Convert-Object-To-Array-With-PHP.html

答案 3 :(得分:1)

您也可以在对象上调用toArray()

$words = ItemPeer::searchFromArticleRequest($this->word);
$wordsArray = array();
foreach ($words as $word)
{
    $wordsArray[] = $word->toArray();
}
return $this->renderText(json_encode($wordsArray));

Propel 1.6 will have a toJSON() method用于单个对象或整个对象集合。