Where is defined the according type for the JSON output in Zend Framework 2?

184 Views Asked by At

I activated the JsonStrategy in a ZF2 application and can get JSON output now using AcceptableViewModelSelector Controller Plugin.

It works only with the HTTP Request parameter Accept containing application/json.

Where is application/json defined as proper value for JSON output? (How) Can I define and use foo/bar instead?

2

There are 2 best solutions below

0
On

Directly in the definition array of the accept criteria:

class SomeController extends AbstractActionController
{
   protected $acceptCriteria = array(
      'Zend\View\Model\JsonModel' => array(
         'application/json', // <-- here
      ),
      'Zend\View\Model\FeedModel' => array(
         'application/rss+xml',
      ),
   );

   public function apiAction()
   {
      $viewModel = $this->acceptableViewModelSelector($this->acceptCriteria);

      // Potentially vary execution based on model returned
      if ($viewModel instanceof JsonModel) {
         // ...
      }
   }
}
1
On

Take a look here:

Zend\View\Strategy\JsonStrategy;

You can implement your own custom strategy in the same manner no problem. Much cleaner than hard coding into the controller as it can be reused.