Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean Ajax controller implementation in Zend Framework

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.

like image 524
Johni Avatar asked Dec 27 '22 15:12

Johni


2 Answers

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 :

//In your controller, activate json context for ANY called action in once

public function init(){
    $action = $this->_getParam('action');
    $this->_helper->getHelper('contextSwitch')
         ->addActionContext($action, 'json')
         ->initContext();
}

And thats all, you don't need any view scripts, all the variables you assign via $this->view will 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

routes.ajax.route = '/ajax/:action/*'
routes.ajax.defaults.controller = ajax
routes.ajax.defaults.action = index
routes.ajax.defaults.format = json
like image 161
Frederik Eychenié Avatar answered Jan 13 '23 10:01

Frederik Eychenié


You can simply use

$this->_helper->json($data);

wherever you like. It disables everything not needed, clears the response, encode data to json, sends the response and set propper headers as a bonus. This is the most "zend-way" there is I guess ;)

like image 35
Tomáš Fejfar Avatar answered Jan 13 '23 10:01

Tomáš Fejfar