问题
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