ZF2 View strategy

2019-05-08 04:08发布

I'm trying to implement the following:

Simple controller and action. Action should return response of 2 types depending on the request:

HTML in case of ordinary request (text\html),
JSON in case of ajax request (application\json)

I've managed to do this via a plugin for controller, but this requres to write

return $this->myCallBackFunction($data)

in each action. And what if I wan't to do this to whole controller? Was trying to figure out how to implement it via event listener, but could not succed.

Any tips or link to some article would be appreciated!

1条回答
女痞
2楼-- · 2019-05-08 04:51

ZF2 has the acceptable view model selector controller plugin specifically for this purpose. It will select an appropriate ViewModel based on a mapping you define by looking at the Accepts header sent by the client.

For your example, you first need to enable the JSON view strategy by adding it to your view manager config (typically in module.config.php):

'view_manager' => array(
    'strategies' => array(
        'ViewJsonStrategy'
    )
),

(It's likely you'll already have a view_manager key in there, in which case add the 'strategies' part to your current configuration.)

Then in your controller you call the controller plugin, using your mapping as the 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 a JsonModel for requests that accept a JSON response (i.e. AJAX requests).

Any variables you assign to the JsonModel will be shown in the JSON output.

查看更多
登录 后发表回答