ZF2 specifically for this purpose has a controller plug-in an acceptable view model selector . It will select the appropriate ViewModel based on the mapping you define by looking at the Accepts header sent by the client.
In your example, you first need to enable the JSON view strategy by adding it to the view manager configuration (usually in module.config.php ):
'view_manager' => array( 'strategies' => array( 'ViewJsonStrategy' ) ),
(You probably already have the view_manager switch, in which case add the βstrategyβ part to your current configuration.)
Then in the controller, you call the controller plugin using your mapping as a parameter:
class IndexController extends AbstractActionController { protected $acceptMapping = array( 'Zend\View\Model\ViewModel' => array( 'text/html' ), 'Zend\View\Model\JsonModel' => array( 'application/json' ) ); public function indexAction() { $viewModel = $this->acceptableViewModelSelector($this->acceptMapping); return $viewModel; } }
This will return a normal ViewModel for standard requests and JsonModel for requests that accept a JSON response (i.e. AJAX requests).
Any variables assigned by JsonModel will be displayed in JSON output.
source share