0

If one needs JSON, XML, etc. als output format, one can use the AcceptableViewModelSelector Controller Plugin or / and (?) alternate rendering / response strategies.

When should the one and when the other (and when a combination) be applied?

Can/should they be combined?

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

3

Well, the Strategies are basically listeners. Listeners that give action depending on what kind of Model will be returned from your Controllers actions. If you return a ViewModel the PhpRendererStrategy will take place. If you return a JsonModel, the JsonStrategy will do it's stuff and if you return a FeedModel it's the FeedStrategy doing it's thing.

However the Strategies only apply if they are registered. So if you return a JsonModel without having the JsonStrategy registered, then nothing will happen.

The AcceptableViewModelSelector exists to provide an easier access and handling of different ModelFormats depending on the accept header. It helps to make things easier, no more, no less.

Strategies, you can also register your own one. There's modules out there that have a PdfStrategy which will render out a PDF-Document if you tell it to.

To tune this down a little to your question:

  • Strategies have been there from the start of ZF 2.0
  • The controller plugin AVMS only got in sometime within ZF 2.1 to just make things easier - that's why it's nothing more than a "plugin" ;)

If that doesn't really cover your question, i'm quite insecure on how to answer you ^^

Sam
  • 16,435
  • 6
  • 55
  • 89
  • That means, if I need several output types depending on the `Accept` value, I have to use a combination of the `AcceptableViewModelSelector` and the strategies? The approach is: (0. Implement the strategy, if a custom one needed.) 1. Register the strategies; 2. Detect the `Accept` value with the `AcceptableViewModelSelector`; 3. (In the Controller action / REST method) Return a `ViewModel` object, supported by one of the registered strategies; 4. The `Zend\View\View` will process the `ViewModel` object according to / using the strategy. Do I understand the approach correectly? – automatix Jun 28 '13 at 20:32
  • I think you got it right even if you think way too complicated. The AVMS is only a HELPER to do the "accept-header-to-rendering-strategy-matching" automatically ;) in the background all AVMS does is to work with the header and select the appropriate rendeirng strategy as well as registering the strategies ;) I think you've got it right tho, even if to me it sounds complicated what you say :D – Sam Jun 28 '13 at 20:59
  • It's beginning to become clear... :) Thank you for your answer and comment! – automatix Jun 28 '13 at 21:25