传递值以在Zend Framework 2中查看 [英] Passing values to view in Zend Framework 2

查看:138
本文介绍了传递值以在Zend Framework 2中查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我们现有的应用程序从Zend Framework 1转换为Zend Framework 2,我有点麻烦。

I'm trying to convert our existing application from Zend Framework 1 to Zend Framework 2 and I'm having a little trouble.

在原始应用程序中

function init()
{
    $this->initialize_values();
}

我所有的控制器都扩展了一个基类, 。

All my controllers extended a base class which had that function in it as seen here.

protected function initialize_values()
{

    $this->_db = Zend_Registry::get('dbAdapter');
    $this->_current_user = new User(&$this->_db);

    $this->_auth = Zend_Auth::getInstance();
    if($this->_auth->hasIdentity())
    {
        $this->_current_user = unserialize($_SESSION['current_user']);
        $this->view->current_user = $this->_current_user;
    }
}

我复制了除最后一行之外的所有功能

I've replicated all the functionality except the last line where I set that view value.

在我为ZF2找到的所有示例中,它们返回一个数组或一个视图模型。我没有看到一个方法传递一个值到视图没有附加到动作函数。

It seems in all the examples I'm finding for ZF2 they are returning an array or a viewmodel. I'm not seeing a way to pass a value to the view not attached to an action function.

推荐答案

这是因为它以创建新的ViewModel()并将其返回到调用脚本。根据从控制器返回的内容,将调用适当的渲染器。

That's because it's up to you to create the new ViewModel() and return it to the calling script. Depending on what you return from your controller, the appropriate renderer gets invoked.

例如,如果我返回一个html块,我会使用

For example if i'm returning a block of html, i'd use

return new ViewModel(array('results' => $results));

但是,如果我想提供JSON输出,我会返回

at the end of my controller action. However, if i wanted to deliver JSON output i would return

return new JsonModel($results);

在您的情况下,您可以准备您的视图模型并将其存储在受保护的变量中,它像这样:

In your case, you could prepare your view model and store it in a protected variable and add variables to it like this:

// in your constructor
$this->_view = new ViewModel();

// in your initialize values method
$this->_view->setVariable($name, $value);

然后当准备输出时:

// in your controller action
return $this->_view;

这篇关于传递值以在Zend Framework 2中查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆