Zend framework2 如何在布局中使用控制器

Zend framework2 如何在布局中使用控制器,zend-framework2,Zend Framework2,您好,我想知道如何在布局视图中获取控制器对象。 我有一个名为MyAbstractAction的类(它有一个getAuthService()方法),它扩展了AbstractAction类,我的所有控制器都扩展了MyAbstractAction 嗯,我想在布局中使用这种方法,但我不能,我试着在布局中使用这种方法 application/module/application/module.php class Module{ public function onBootstrap(MvcEven

您好,我想知道如何在布局视图中获取控制器对象。 我有一个名为MyAbstractAction的类(它有一个getAuthService()方法),它扩展了AbstractAction类,我的所有控制器都扩展了MyAbstractAction

嗯,我想在布局中使用这种方法,但我不能,我试着在布局中使用这种方法 application/module/application/module.php

class Module{
    public function onBootstrap(MvcEvent $e)
    {

            $e->getApplication()->getServiceManager()->get('translator');
            $eventManager   = $e->getApplication()->getEventManager();
            $viewModel = $e->getViewModel();
            $c= $e->getController();
            $authService = $this->getAuth($e);  
            if($authService){
                  $viewModel->setVariable('controller',$c);
            }
            if($this->getAuth($e)->hasIdentity()){
                  $viewModel->setTemplate('layout/inside');
            }else{
                  $viewModel->setTemplate('layout/outside');      
            }
       }
     //More methods

}
但它不起作用,有人能告诉我怎么做

这是我的类MyAbstractActionController,MyAbstractActionController方法仅从service manager提供服务:

class MyAbstractActionController extends AbstractActionController 
{
    public $authService;
            public $sm;
            public $sessionStorage;
            public $dbAdapter;
            public function getAuthService()
    {
                error_log("Ejecutando:".__METHOD__);
        if(!$this->authService)
        {
                    $this->authService = $this->getServiceLocator()->get('Auth\AuthService');
        }
                  return $this->authService;
    }
    public function getDbAdapter()
       {
          if(!$this->dbAdapter)
        {
                    $this->dbAdapter = $this->getServiceLocator()->get("Zend\Db\Adapter\Adapter");
        }
                  return $this->dbAdapter;
      }


      public function getSessionStorage()
      {
            error_log('Ejecutando: ' . __METHOD__);
            if(!$this->sessionStorage)
            {
                  $this->sessionStorage = $this->getServiceLocator()->get('Auth\Storage\MySessionStorage');

            }
            return $this->sessionStorage;
      }
}

提前感谢:)

能否显示相关控制器和布局中的一些代码,以及您希望在布局中使用控制器(或是AuthService?)做什么。如果您需要访问布局中的控制器,听起来您的设计有严重问题。您不能在视图中使用控制器,这违反了层分离。无论您在控制器中放置了什么,都应该移动到应用程序服务,并通过视图帮助器公开给视图。我已经更新了我的帖子,getAuthService方法只会将service Manager中的AuthService(我的代码类似于Abdul的代码)带到控制器。如果我做不到,我怎么能让它工作?对不起,我是西班牙人,也许我的英语不好。谢谢。顺便说一句。我需要带上AuthService,因为我想检查用户是否已登录(如果用户已登录,则会显示其他html代码),例如:if($this->getAuthService()->hasIdentity()){//code for allowed users}else{//code for not allowed users}您可以为自己编写一个
ViewHelper
,然后注入
Auth\AuthService
。然后,您可以执行类似于
$this->myHelper()->hasintity()
的操作,就这么简单