I need a controller in my Zend Framework project, which should handle only ajax requests.
My approach at the moment is to extend the Zend_Controller_Action:
class Ht_Ajax_Controller extends Zend_Controller_Action{
public function preDispatch(){
$this->getResponse()->setHeader('Content-type', 'text/plain')
->setHeader('Cache-Control','no-cache');
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
}
public function outputJson($data){
$this->getResponse()->setBody(json_encode($data))
->sendResponse();
exit;
}
}
Although, I know this isn’t the recommended way to do so in Zend Framework. So that’s why I am asking, how to make this in Zend’s way ?
The first thing I thought about was to make a controller plugin, but how can I register this plugin easily? The bootstrap is no option because I need this only for specific controllers. And to register it inside the controller in a very early state seems not very clean.
So how should I implement my Ajax Controller? I also know there is the extended Context switching helper ,however I think that way has too much overhead for just setting the content type etc.
markus explained the most “Zend Like” way and his explanation is correct. But you see it as too much overhead because he missed to show you how much the “json context switch” is the best for your case.
Look how short it is :
And thats all, you don’t need any view scripts, all the variables you assign via
$this->viewwill be serialized into a JSON object.Oh and you don’t want to add the context in the urls? Ok, just activate it by default in your route