0

我从一个控制器的操作方法调用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 Zend\View\Model\ViewModel
        $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页面的 ViewModel:

Zend\View\Model\ViewModel 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

更新 1

现在只在这里找到这个:

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

这不起作用:

$this->getEvent()->setResult(array(
                'one' => 'value one',
                'two' => 'value two',
                'three' => 'value three',
            ));

return $this->getEvent()->getResult();  // doesn't work, returns ViewModel anyway

这意味着我必须将变量放入 a ViewModel,返回 aViewModel并从ViewModel. 非常好的设计,我可以说。

4

1 回答 1

2

您必须在 ZF2 中的操作中禁用视图。你可以这样做:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

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;
    }
}
于 2012-12-12T21:12:19.930 回答