dpntq48842 2009-05-14 23:25
浏览 28
已采纳

如何在所有控制器中集中我的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;
    }

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?

  • 写回答

3条回答 默认 最新

  • douanye8442 2009-05-15 00:11
    关注

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

    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()
        {
            // ...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案