如何在所有控制器中集中来自我的 init 函数的代码? [英] How do I centralize code from my init functions in all controllers?
本文介绍了如何在所有控制器中集中来自我的 init 函数的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public function init(){
$this->view->user = Zend_Auth::getInstance()->getIdentity();
$this->view->siteName = Zend_Registry::get('config')->site->name;
$this->view->menu = $this->_helper->generateMenu(Zend_Auth::getInstance()->getIdentity());
$this->view->slogan = Zend_Registry::get('config')->site->slogan;
}
这是我所有模块中所有控制器中的 init 文件,有没有地方可以放置此代码,以便它执行每个请求,而不管模块/控制器是否被调用?
This is the init file in all of my controllers across all modules, is there a place I can put this code so it executes every request irregardless of the module/controller being called?
推荐答案
你可以扩展 Zend_Controller_Action:
You can extend Zend_Controller_Action:
public class My_Controller_Action extends Zend_Controller_Action
{
public function init()
{
$this->view->user = Zend_Auth::getInstance()->getIdentity();
$this->view->siteName = Zend_Registry::get('config')->site->name;
$this->view->menu = $this->_helper->generateMenu(Zend_Auth::getInstance()->getIdentity());
$this->view->slogan = Zend_Registry::get('config')->site->slogan;
}
}
然后您只需更改控制器以扩展 My_Controller_Action 而不是 Zend_Controller_Action.请记住,如果您需要向控制器的 init 方法添加其他代码,则还必须调用 parent::init():
Then you just change your controllers to extend My_Controller_Action rather than Zend_Controller_Action. Just keep in mind that if you need to add additional code to the init method of a controller, you'll have to invoke parent::init() as well:
public class FooController extends My_Controller_Action
{
public function init()
{
parent::init();
// Do something.
}
public function IndexAction()
{
// ...
}
}
这篇关于如何在所有控制器中集中来自我的 init 函数的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文