jsonzend-framework2zend-view

How to return JsonModel by default in ZF2?


Default ViewModel is not mandatory, I can return from controller just the array of data:

public function someAction()
{
  //...
  return array('result'=>$data);
}

But I can`t use this approach with Json. What should I do in dispatch event to wrap the results in JsonModel (for the appropriate accept header)?


Solution

  • Just create Base Controller for all your API controllers, and replace model in MvcEvent.

    class JsonRestController extends AbstractRestfulController
    {
    
        public function onDispatch(MvcEvent $e)
        {
            $e->setViewModel(new JsonModel());
            return parent::onDispatch($e);
        }
    }