Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does rendering / response strategy mean in Zend Framework 2 and how to use it?

The ZF2 docu describes Creating and Registering Alternate Rendering and Response Strategies. I've read that, but I don't really understand, how to use a strategy.

I have an application, that should ship three types of output (JSON, XML, and HTML), depending on the HTTP header accept. How can I use the strategies for this case?

like image 654
automatix Avatar asked Jun 25 '13 07:06

automatix


1 Answers

The loose concept of a strategy in Zend Framework 2 is the behavior that the application should follow when events are triggered during the MVC application cycle, that being in fact event driven.

In more practical terms, a strategy is basically an event listener, usually a concrete instance of \Zend\EventManager\AbstractListenerAggregate, and usually listens to \Zend\Mvc\MvcEvent various events like EVENT_RENDER and EVENT_RENDER_ERROR.

The listener is attached to the \Zend\EventManager\EventManager and then, using the aformentioned \Zend\Mvc\MvcEvent to access all the fundamental resources of the MVC cycle (router, request, response, the application itself, etc), the listener can inspect the status of the application and alter its flow.

In the example provided by ZF2 official docs, the listener inspects the request's accept headers, selects a renderer and alters the response accordingly.

It is a bit old though, so I'd suggest to look at some better examples reading the code of the staple strategies provided by the framework, i.e. \Zend\Mvc\View\Http\RouteNotFoundStrategy which listens to EVENT_DISPATCH and EVENT_DISPATCH_ERROR to handle the rendering of 404 error pages.

Also it is vitally important that you understand how the whole EventManager works. Official docs for that are quite good, plus there is a lot of stuff about it if you google around.

like image 66
Stefano Torresi Avatar answered Nov 15 '22 20:11

Stefano Torresi