I 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 first thing you need to do, is to create a simple Controller Request object 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);
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();
Once you have your dispatcher, just call the dispatch method and pas your request & 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();
This is the entire block of code. I have used it in view helpers, but you can also implement it as a plugin.
<?php $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(); ?>