Tuesday, January 01, 2008

Try Zend Framework vol.9 "Adding Json method on Rowset class"

Recently I started to study javascript and it's pretty interesting to use ajax.
When you deal with ajax, you probably want to get data as JSON. Don't you?

Zend Framework has data set handling class which is called
"Zend_Db_Table_Row" and "Zend_Db_Table_Rowset". And they have data conversion method "toArray()"

If they have JSON conversion method like "toJson()", it's helpful. isn't it? :)

Ok, Let's say you have data like below. We are going to convert this data to JSON.
mysql> select * from data;
+----+---------+
| id | data |
+----+---------+
| 1 | data 1 |
| 2 | data 2 |
| 3 | data 3 |
| 4 | data 4 |
| 5 | data 5 |
+----+---------+


Add a new method toJson() on Row class.
library/Hoge/Db/Table/Row.php
<?php
/**
* @see Zend_Db_Table_Row
*/
require_once 'Zend/Db/Table/Row.php';

class Hoge_Db_Table_Row extends Zend_Db_Table_Row
{
/**
* Returns the column/value data as json.
*
* @return string
*/
public function toJson()
{
require_once 'Zend/Json.php';
return Zend_Json::encode($this->_data);
}
}


For Rowset class.
library/Hoge/Db/Table/Rowset.php
<?php
/**
* @see Zend_Db_Table_Rowset
*/
require_once 'Zend/Db/Table/Rowset.php';

class Hoge_Db_Table_Rowset extends Zend_Db_Table_Rowset
{
/**
* Returns all data as a json.
*
* @return string
*/
public function toJson()
{
require_once 'Zend/Json.php';
return Zend_Json::encode($this->_data);
}
}


Ok, Let's use these extended classes.
There are several ways to specify these new classes.

1.Set names of these classes via setter methods.
application/controllers/HogeController.php

function jsonAction() {
require_once 'Hoge/Db/Table/Data.php';
$data = new Data();
$data->setRowClass('Hoge_Db_Table_Row');
$data->setRowsetClass('Hoge_Db_Table_Rowset');
$res = $data->fetchAll()->toJson();
print_r($res);
exit;
}


2.Set names of these classes in the Table_Abstract class.
library/Hoge/Db/Table/Abstract.php
<?php
require_once 'Zend/Db/Table/Abstract.php';

abstract class Hoge_Db_Table_Abstract extends Zend_Db_Table_Abstract
{

public function __construct()
{
$config = array(
'rowClass' => 'Hoge_Db_Table_Row',
'rowsetClass' => 'Hoge_Db_Table_Rowset'
);
parent::__construct($config);
}
}


To use toJson() method. The usage is same as toArray() method.
application/controllers/HogeController.php

function jsonAction()
{
require_once 'Hoge/Db/Table/Data.php';
$data = new Data();
$res = $data->fetchAll()->toJson();
print_r($res);
exit;
}


It returns JSON data like below.
[{"id":"1","data":"data 1"},{"id":"2","data":"data 2"},{"id":"3","data":"data 3"},{"id":"4","data":"data 4"},{"id":"5","data":"data 5"}]

(weight 89.0kg BMI 31%)

Labels:

0 Comments:

Post a Comment

<< Home