A free and open-source book on ZF3 for beginners


4.17. View Rendering Strategies

A rendering strategy determines how the page will be rendered. By default, to produce the HTML page, the .phtml view template is rendered with the help of PhpRenderer class living in Zend\View\Renderer namespace. This strategy works well in 99% of cases. But sometimes you may need to return something else, for example, a JSON response or a RSS feed response.

A response in JSON format is typically returned when you implement some kind of API (Application Programming Interface). API is used to retrieve some the data in machine-readable format. A response in RSS feed format is typically used to publish frequently changing information, like blog posts or news.

So, ZF3 provides three view rendering strategies out of the box:

4.17.1. Returning JSON Response

For example, let's show how to use JsonStrategy to return JSON response from a controller action.

First, you'll need to register the strategy in module.config.php configuration file:

<?php
return [
    //...
    
    'view_manager' => [
        //...
        
        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],
];

Then, return JsonModel (instead of the usual ViewModel) from your controller's action method:

namespace Application\Controller;
 
use Zend\Mvc\Controller\ActionController;
use Zend\View\Model\JsonModel;
 
class IndexController extends ActionController
{
    public function getJsonAction()
    {
        return new JsonModel([
            'status' => 'SUCCESS',
            'message'=>'Here is your data',
            'data' => [
                'full_name' => 'John Doe',
                'address' => '51 Middle st.'
            ]
        ]);
    }
}

If you open the page http://localhost/application/get-json in your browser, you will see JSON response:

{'status':'SUCCESS', 'message':'Here is your data', 'data':{'full_name:'John Doe', 'address':'51 Middle st.'}}

Top