Zend 2: Where should I put this method that updates a module's nav bar

孤人 提交于 2019-12-10 23:54:38

问题


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

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';
}

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.

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.


回答1:


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))
    }
}

in your modules config file

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

in layout

$this->mynav();


来源:https://stackoverflow.com/questions/22309922/zend-2-where-should-i-put-this-method-that-updates-a-modules-nav-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!