понедельник, 3 июня 2013 г.

DISPATCHING HTTP REQUESTS MANUALLY IN ZEND FRAMEWORK

http://blog.feryn.eu/2011/02/dispatching-http-requests-manually-in-zend-framework/

recently developed a custom Zend Framework view helper and I needed to find a way to get pieces of rendered HTML out of an action controller.
You could to this in a simple way by performing a full HTTP call via cURL. That’s not the best way to get it done, so I started looking under the hood of Zend Framework.
What I’ve found is that the core of the MVC is the dispatcher. In the entire MVC cycle, it gets called and returns your HTML as the body of your HTTP response object. Digging into it was simpler than expected and therefor I would like to share the code I used to dispatch a request.

THE REQUEST

The first thing you need to do, is to create a simple Controller Requestobject that contains the action and the controller you wish to dispatch. Eventually the object is passed to your dispatcher.
$request = new Zend_Controller_Request_Simple($action, $controller);

THE RESPONSE

You also have to create an empty Controller Response object that will also be passed to the dispatcher. The dispatcher stores the HTML in this object.
$response = new Zend_Controller_Response_Http();

ACCESSING THE DISPATCHER

Accessing the dispatcher is quite easy: it’s part of the front controller and the front controller instance is a singleton pattern. It is accessible from any context within the MVC cycle.
$frontController = Zend_Controller_Front::getInstance();
$dispatcher = $frontController->getDispatcher();

DISPATCHING

Once you have your dispatcher, just call the dispatch method and pas yourrequest & response as arguments. The dispatcher stores the results in your response object and by calling the getBody() method, you will have the rendered HTML.
$dispatcher->dispatch($request, $response);
echo $response->getBody();

SUMMARY

This is the entire block of code. I have used it in view helpers, but you can also implement it as a plugin.

$request = new Zend_Controller_Request_Simple($action, $controller);
$response = new Zend_Controller_Response_Http();
$frontController = Zend_Controller_Front::getInstance();
$dispatcher = $frontController->getDispatcher();
$dispatcher->dispatch($request, $response);
echo $response->getBody();
?>