【问题标题】:Where is defined the according type for the JSON output in Zend Framework 2?Zend Framework 2 中 JSON 输出的相应类型在哪里定义?
【发布时间】:2013-07-18 12:36:40
【问题描述】:
【问题讨论】:
标签:
json
zend-framework2
http-accept-encoding
【解决方案1】:
直接在接受条件的定义数组中:
class SomeController extends AbstractActionController
{
protected $acceptCriteria = array(
'Zend\View\Model\JsonModel' => array(
'application/json', // <-- here
),
'Zend\View\Model\FeedModel' => array(
'application/rss+xml',
),
);
public function apiAction()
{
$viewModel = $this->acceptableViewModelSelector($this->acceptCriteria);
// Potentially vary execution based on model returned
if ($viewModel instanceof JsonModel) {
// ...
}
}
}
【解决方案2】:
看这里:
Zend\View\Strategy\JsonStrategy;
您可以以同样的方式实施您自己的自定义策略,这没有问题。比硬编码到控制器中要干净得多,因为它可以重复使用。
【讨论】:
-
你的意思是使用策略而不是 AcceptableViewModelSelector?我想,我必须使用AcceptableViewModelSelector 和策略的组合?方法是:(0. 实施策略,如果需要自定义策略。) 1. 注册策略; 2、用AcceptableViewModelSelector检测Accept值; 3.(在Controller动作/REST方法中)返回一个ViewModel对象,由其中一种注册策略支持; 4.Zend\View\View将根据选择的策略处理ViewModel对象(见stackoverflow.com/a/17350883/2019043)。