ZF2 View strategy

旧时模样 提交于 2019-12-05 14:28:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!