Pragmatism in the real world

Returning JSON from a ZF2 controller action

The new view layer in Zend Framework 2 can be set up to return JSON rather than rendered HTML relatively easily. There are two steps to this:

Set up the JsonStrategy

Firstly we need to set up the view’s JsonStrategy to check to a situation when returning JSON is required and then to render out JSON for us. The JsonStrategy will cause the JsonRenderer to be run in two situations:

  1. The view model returned by the controller action is a JsonModel
  2. The HTTP Accept header sent in the Request include “application/json”

To enable the JsonStrategy, we simply configure it in the module’s config.php file:

module/Application/config/module.config.php:

    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
            'index/index'   => __DIR__ . '/../view/index/index.phtml',
            'error/404'     => __DIR__ . '/../view/error/404.phtml',
            'error/index'   => __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            'application' => __DIR__ . '/../view',
        ),
        'strategies' => array(
            'ViewJsonStrategy',
        ),
    ),

As you can see, in the view_manager() add ViewJsonStrategy to the strategies array.

Return a JsonModel from the controller action

To send JSON to the client when the Accept header isn’t application/json, we use a JsonModel in a controller action like this:

module/Application/src/Application/Controller/IndexController.php:

namespace Application\Controller;

use Zend\Mvc\Controller\ActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;

class IndexController extends ActionController
{
    public function indexAction()
    {
        $result = new JsonModel(array(
	    'some_parameter' => 'some value',
            'success'=>true,
        ));

        return $result;
    }
}

The output will now be JSON. Obviously, if you’re sending JSON back based on the Accept header, then you can return a normal ViewModel.

Note that this entry was updated on 20 June 2012 to reflect updates to ZF2.

See also: Returning JSON using the Accept header in ZF2