ZF2 - Forward Plugin返回ViewModel对象。如何使其返回其他值,例如简单或关联数组?

时间:2012-12-12 15:42:31

标签: zend-framework2 zend-framework-mvc zend-framework-routing

我从一个Controller的action方法中调用the Forward plugin来从另一个Controller的action方法中获取值:

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获取所需的数据类型?

UPD 1

现在只找到here

  

MVC为控制器注册了几个用于自动化的监听器   这个。第一个将查看是否返回了关联数组   来自你的控制器;如果是这样,它将创建一个View Model并制作它   关联数组变量容器;这个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

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

1 个答案:

答案 0 :(得分: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;
    }
}