I had a play with the AjaxContext code that Matthew posted to the laboratory and it’s quite nice.
This is how I set it up.
Firstly I grabbed the files from the laboratory subversion repository and placed them in my lib/ directory. I then took updated my path using setincludepath() ensuring that the new folder was first in the list.
Having set up the environment, I then loaded the action helper in my bootstrap:
[php]$ajaxContext = new ZendControllerActionHelperAjaxContext();
ZendControllerAction_HelperBroker::addHelper($ajaxContext);[/php]
Which is nice and easy!
We are now able to make an action ajaxable. I pulled out the feedback action in the review controller within the Places example application. This action is already “ajaxed” and so the view scripts create an XmlHttpRequest to the action and know how to respond when Json is returned. Ideal for testing the context helper.
In the ReviewController, you need to add a new public member variable called $ajaxable:
[php]class ReviewController extends ZendControllerAction
{
public $ajaxable = array(‘feedback’=>array(‘json’));
// continues
[/php]
The array contains a list of actions within this controller than may receive Ajax requests and a list of acceptable formats. In our case, we only support json, but you could equally support xml, html csv or plain text depending on the use of the action.
We then need to initialise the context in preDispatch():
[php]
public function preDispatch()
{
$this->request->setParam(‘format’, ‘json’);
$this->helper->ajaxContext()->initContext();
}
[/php]
It is intended that you can pass through which context you want using a request variable called ‘format’. Unfortunately, you can’t not have it in the request at the moment. This bug will be fixed
initContext() is actually quite a simple function. It does lots of checking to ensure that the context needs to be changed and then it changed the suffix for the view scripts to {format}.phtml, sets a content type header in the response and finally disables Zend_Layout’s layout system (if it’s in use).
In this case, the view script that is now rendered is called feedback.json.phtml which contains the following:
[php]
<?php
echo ZendJson::encode(getobject_vars($this));
[/php]
This simply encodes all the variables that have been assigned to the view into Json format.
The processing of the request continues as normal and a little later, at the end of the dispatch cycle, the response is echoed back the browser with a nicely formatted Json object as intended.
Posted by Rob on 7th January 2008 under The Book | 6 Comments »