Marrying the Zend Framework and HTML Ajax


Update: Since writing this I’ve instead started using jQuery for my Ajax needs, you should too, or MooTools maybe. I’ve written a new piece demonstrating how jQuery can be used with ZF.

What if you want to use some HTML Ajax without having to move code from the controller? The answer is that you have to be able to make instances of each controller.

Start with the class you extend Zend_Controller_Action with. My constructor in that class looks like this:

function __construct($request = false, $response = false, $invokeArgs = false){
	if(!$request)
		$request = new Zend_Controller_Request_Http();
	
	if(!$response)
		$response = new Zend_Controller_Response_Http();
	
	if(!$invokeArgs)
		$invokeArgs = array();
	
	parent::__construct($request, $response, $invokeArgs);
}

The extra lines are necessary because you won’t have valid request and response objects when you instatiate a controller so they need to be created if they don’t exist.

Next you could create a factory function in the class that handles the ajax requests, it can look something like this:

function loadController($controller){
	$class_name = ucfirst($controller)."Controller";
	$file_name = "controllers/".$class_name.".php";
	include_once($file_name);
	$ctrl = new $class_name;
	return $ctrl;
}

Finally you are ready to use this to actually do something useful:

function searchResult($post, $id, $controller){
	$post           = unserialize($post);
	$ctrl             = $this->loadController($controller);
	$inner_html  = $ctrl->getSearchResult($post, false, true);
	$attr_arr = array(
		'innerHTML' => $inner_html,
		'class'		=> 'subform_container'
	);
	$this->response->assignAttr($id, $attr_arr);
	return $this->response;
}

In the above example some kind of search form is serialized and passed to php from a javascript. It is unserialized and passed to an instance of a controller. We recieve the output which is generated by a Smarty object with the fetch() function called in the getSearchResult() function of the controller.

The above way of doing things enables us to keep as much of the logic as possible where it is supposed to be, in the controllers. I hope this post was useful.

Related Posts

Tags: , ,