0

Using Zend Framework 2 and an AbstractRestfulController where the getList action is implemented like this:

public function getList() {
    return new ViewModel(array(
        'entities' = array(1 => array(/*..*/), 2 => array(/*..*/))
    ));
}

I've added the JsonStrategy to the view manager so when my UA sends Accept: text/html ZF2 uses the correct view to format the data. When my UA sends Accept: application/json ZF2 (correctly) responds with application/json and JSON encodes the data.

But now the all the entities are wrapped inside a 'content' node (the ViewModel::$captureTo property).

If the action controller returns a JsonModel I can avoid this. But then the JsonStrategy always responds with application/json, without checking Accept.

Is there any way to avoid it while still using the ViewModel, and not the JsonModel?

4

2 回答 2

1

为了获得解决方案,我做了这样的事情:

1 - 创建一个新的 MasterControllerClass,我的新控制器“扩展 MasterControllerClass”

abstract class MasterControllerClass extends AbstractActionController 
private $_jsonFlag = false;

public function onDispatch(MvcEvent $e)
{
    $this->preDispatch($e);
    $action = parent::onDispatch($this->getEvent());
    $this->postDispatch($e);
    return $action;
}

public function postDispatch(MvcEvent $e)
{
    $this->_jsonFlag ?: $this->viewConfig($e);
}

public function json($value, $sucess = true)
{
    $this->_jsonFlag = true;
    return new \Zend\View\Model\JsonModel(array(
        'data' => $value,
        'success' => $sucess,
    ));
}

2 - 在我的控制器中我将调用 $this->json('values to pass to javascript', true or false, true == success, false == fail)

它解决了我的问题,现在我可以将 json 传递给我的 javascripts。

于 2012-11-08T12:31:17.117 回答
0

Zend Framework 2.0.4中已经解决了这个问题,但不是很完美。他们添加了一个名为的新控制器插件acceptableViewModelSelector,可以像这样使用它:

class SomeController extends AbstractActionController
{
    protected $acceptCriteria = array(
        'Zend\View\Model\JsonModel' => array(
            'application/json',
        ),
        '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) {
            // ...
        }
    }
}

当它选择创建 JsonModel 时,响应将在没有“内容”包装器的情况下正确呈现。希望有一个更优雅的解决方案,这样人们就可以避免控制器中的视图逻辑,但该修复程序并不是为了直接解决问题而创建的。

于 2012-11-28T12:03:44.570 回答