ZF2 - 前向插件返回视图模型对象.如何使其返回其他值,例如简单或关联数组



我从一个控制器的操作方法调用the Forward plugin,以从另一个控制器的操作方法获取值:

namespace Foo/Controller;
class FooController {
    public function indexAction() {
        // I expect the $result to be an associative array,
        //    but the $result is an instance of the ZendViewModelViewModel
        $result = $this->forward()->dispatch('Boo/Controller/Boo', 
                                              array(
                                                  'action' => 'start'
                                             ));
    }
}

这是我申请Boo控制器:

namespace Boo/Controller;
class BooController {
    public function startAction() {
        // I want this array to be returned,
        //     but an instance of the ViewModel is returned instead
        return array(
            'one' => 'value one',
            'two' => 'value two',
            'three' => 'value three',
        );
    }
}

如果我print_r($result)它是error/404页面的视图模型:

ZendViewModelViewModel Object
(
    [captureTo:protected] => content
    [children:protected] => Array
        (
        )
    [options:protected] => Array
        (
        )
    [template:protected] => error/404
    [terminate:protected] => 
    [variables:protected] => Array
        (
            [content] => Page not found
            [message] => Page not found.
            [reason] => error-controller-cannot-dispatch
        )
    [append:protected] => 
)

这是怎么回事?如何更改此行为并从the Forward plugin获取所需的数据类型?

UPD 1

现在只在这里找到这个:

MVC 为控制器注册几个侦听器以自动执行 这。第一个将查看您是否返回了关联数组 从您的控制器;如果是这样,它将创建一个视图模型并制作 关联数组变量容器;这个视图模型然后 替换 MvcEvent 的结果。

这不起作用:

$this->getEvent()->setResult(array(
                'one' => 'value one',
                'two' => 'value two',
                'three' => 'value three',
            ));
return $this->getEvent()->getResult();  // doesn't work, returns ViewModel anyway

这意味着我必须将变量放入ViewModel中,而不是只获取一个数组,返回一个ViewModel并从ViewModel中获取这些变量。非常好的设计,我可以说。

您必须在

ZF2 中的操作中禁用视图。您可以通过以下方式执行此操作:

namespace ApplicationController;
use ZendMvcControllerAbstractActionController;
class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $result = $this->forward()->dispatch('Application/Controller/Index', array( 'action' => 'foo' ));
        print_r($result->getContent());
        exit;
    }
    public function fooAction()
    {
        $response = $this->getResponse();
        $response->setStatusCode(200);
        $response->setContent(array('foo' => 'bar'));
        return $response;
    }
}

最新更新