如何在多个控制器之间共享一个对象(例如Zend_Auth的实例)


How to share an object (e.g. instance of Zend_Auth) between multiple controllers

我在Zend框架1中有我的应用程序。我使用Zend_Auth来管理会话。下面是我如何在IndexController类中检查身份验证:

class IndexController extends Zend_Controller_Action
{
    public function init()
    {
      $auth = Zend_Auth::getInstance();
      if ($auth->hasIdentity()) {
        $this->view->user = $auth->getIdentity();
      }
    }
    public function indexAction()
    {
    }
}

基本上它只是将user的视图变量设置为auth对象中的值。在我的视图中,我可以检查用户变量是否设置并采取适当的行动(例如显示"欢迎Tom!"和注销链接)

然而,这个功能在我的其他控制器中还不可用。与其在每个init()方法中重复相同的代码,我该如何做到这一点?我不确定该把代码放在哪里。

更新:

我尝试在引导文件中做这样的事情:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  protected function _initView() {
    $auth = Zend_Auth::getInstance();
    if ($auth->hasIdentity()) {
      $this->view->user = $auth->getIdentity();
    }
  }
}

. .但我得到以下错误:Notice: Indirect modification of overloaded property Bootstrap::$view has no effect in /var/www/budgetz/application/Bootstrap.php on line 9 Warning: Creating default object from empty value in /var/www/budgetz/application/Bootstrap.php on line 9

您可以像这样使用继承自Zend_Controller_Action的抽象类:

abstract Class Yourlibrary_Controller_ControllerAbstract extends Zend_Controller_Action
{
    public function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $this->view->user = $auth->getIdentity();
        }
    }
}

您的控制器继承Yourlibrary_Controller_ControllerAbstract而不是Zend_Controller_Action