There are three basic ways that you can achieve that. First of all what’s the task? You’ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array)
// IndexController.php class IndexController extends Zend_Controller_Action { public function indexAction() { $data = array(...); $this->view->data = Zend_Json::encode($data); } } |
The result in general is a specially formatted string. So you can simply set it up to a view member variable and pass it to the view.
// index/index.phtml echo $this->data |
In that case you’ve a .phtml file to maintain, so lets just return the string and “setNoRender” the view in our second try.
// IndexController.php class IndexController extends Zend_Controller_Action { public function indexAction() { $data = array(...); echo Zend_Json::encode($data); $this->_helper->viewRenderer->setNoRender(true); } } |
Actually this is pretty much the most clear solution, but actually you can output the JSON string and simply exit() as it’s shown in our third example.
// IndexController.php class IndexController extends Zend_Controller_Action { public function indexAction() { $data = array(...); echo Zend_Json::encode($data); exit(); } } |
Which one is to be used is up to the developer’s choice, mine is the third one as it’s the minimal one.
Please, consider the most elegant one (better than these ones): ContextSwitch or AjaxContext
The ContextSwitch action helper is intended for facilitating returning different response formats on request. The AjaxContext helper is a specialized version of ContextSwitch that facilitates returning responses to XmlHttpRequests.
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
I prefer the json action helper:
$this->_helper->json($data);
…and you’re done.
Just use $this->getHelper(‘json’)->senJson($data) and all the headers will be correct – I dislike the ‘direct’ calls in those action helpers.
Please don’t use the third method (exit), because then existing postDispatch methods or -plugins are not executed!
The second solution or ContextSwitch/AjaxSwitch is the best choice.
Its not always what or how we prefer doing things, most of the time one should stick to the official methods/ways of doing stuff.
I think this is the significant different between Zend Framework and other frameworks, ZF enforces good coding practices.
If you want to “roll your own” in a variety of ways then rather use other frameworks like Codeigniter, Yii etc.
Although ZF can be extended to suit your needs 100%, a solid convention for doing this also exist – with ZF is hardly ever a case of “where the hell do I find this method” or “Why are these classes but these ones are global functions”…like in Codeigniter etc.