Zend 2:我应该把这个更新模块导航栏的方法放在哪里 [英] Zend 2: Where should I put this method that updates a module's nav bar

查看:28
本文介绍了Zend 2:我应该把这个更新模块导航栏的方法放在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前问过一个问题,关于有哪些选项可用于在每个模块的基础上自动注入导航栏(模板).

I previously asked a question about what options are available to inject a navbar (template) automatically on a per module basis.

按照其中一项建议,我在 Myapp/Module/Mymodule/Module.php 中添加了一个视图变量,这是模板的路径

Following one of the suggestions I added a view variable in Myapp/Module/Mymodule/Module.php which is the path of the template

public function onBootstrap($e) {
    $viewModel = $e->getApplication()->getMvcEvent()->getViewModel();
    $viewModel->subNav = 'mymodule/mymodule/subNav';
}

然后在Application/view/layout/layout.phtml中检查这个变量的存在并显示出来:

Then in the Application/view/layout/layout.phtml checked for the presence of this variable and displayed it:

        <?php if($this->subNav) : ?>
        <nav class="navbar navbar-inverse" role="navigation">
            <?php echo $this->partial($this->subNav); ?>
        </nav>
        <?php endif ?>

这与我想要的完全一样,但现在我想从数据库传递模板动态数据.

This works exactly like I want it to, but now I want to pass the template dynamic data from a database.

所以我的问题是:在 Module.php 中这样做可以吗?在 onBootstrap() 中,我想调用我的数据模型来访问我的数据库并将结果存储在视图变量中.这是对 Module.php 的滥用吗?这种操作应该在控制器中完成,但我希望自动注入这个模板,而我的控制器不必知道它.我是 MVC 和 Zend 的新手,希望确保我没有违反一些基本的设计原则.

So my question is this: Its OK to do this in Module.php right? In onBootstrap() I want to call my data model to access my DB and store the results in a view variable. Is this misuse of Module.php? This kind of operation is supposed to be done in a controller, but I want this template to be injected automatically without my controller having to know about it. I'm new to MVC and zend and want to make sure I'm not violated some fundamental design principle.

推荐答案

创建自定义视图助手,在其中加载数据并渲染视图并在布局中使用它

create a custom view helper , load your data in it and render the your view and use it in the layout

namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;

class MyNav extends AbstractHelper{

    public function __invoke(){
        //load your data

        return $this->view->render('my nav view script',array('data'=>$data))
    }
}

在你的模块配置文件中

'view_helpers' => array(
    'invokables' => array(
        'mynav'  => 'Application\View\Helper\MyNav',
    ),  
),

在布局中

$this->mynav();

这篇关于Zend 2:我应该把这个更新模块导航栏的方法放在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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