In Zend Framework 2, I want to return JSON if the HTTP accept header is set to "application / json" and HTML otherwise. I am using the new controller plugin acceptableViewModelSelector , as in the example in change list 2.0.4 .
I have the following code:
class IndexController extends AbstractActionController { private $acceptCriteria = array( 'Zend\View\Model\JsonModel' => array('application/json'), 'Zend\View\Model\FeedModel' => array('application/rss+xml') ); public function jsonAcceptHeaderAction() { $view_model = $this->acceptableViewModelSelector($this->acceptCriteria); return $view_model; } }
If I set the accept header as follows:
curl -H "Accept: application/json" http://mydomain.com/json
The controller plugin then returns an instance of JsonModel as expected. However, this seems to always happen, even if there is no application/json in my accept header. For example, if I visit a page in Chrome, the following receiving headers are sent:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
I also get JSON if I use curl http://mydomain.com/json . The controller plugin has a default view model name, which I expected to be used when it does not match my acceptance criteria. The change log indicates the following:
The above will return a standard instance of Zend \ View \ Model \ ViewModel if the criteria are not met, and the specified types of the view model if specific criteria are met.
I tried changing the accept criteria to the following, which turned out to do what I wanted.
private $acceptCriteria = array( 'Zend\View\Model\ViewModel' => array('text/html'), 'Zend\View\Model\JsonModel' => array('application/json'), 'Zend\View\Model\FeedModel' => array('application/rss+xml') );
I'm just wondering why it doesn't use the default view model name when there is no application/json accept header, because ideally I would like to leave the first entry in my array of acceptance criteria.
Does anyone know why I always get a JsonModel object if I don't do it above?