0

我想设置一个basePath对于给定请求的我的Mvc的每个组件都是一样的。我的意思是,当我调用这些方法我想获得相同的结果,可以说'/spam/ham/'ZF2:如何在Module类中的事件上附加监听器?

echo $this->headLink()->prependStylesheet($this->basePath() . '/styles.css') // $this->basePath() has to be '/spam/ham/' 

$this->getServiceLocator() 
    ->get('viewhelpermanager') 
    ->get('headLink') 
    ->rependStylesheet($this->getRequest()->getBasePath() . '/styles.css') // $this->setRequest()->getBasePath() has to be /spam/ham/ 

如何设置basePath对于第一种情况,我发现已经,here's my question。顺便说一句,原来的手册没有我从答案中收到的任何信息。

而现在的第二个 - 在basePath已在Request进行设置:

$this->getRequest()->getBasePath() 

在这里,我找到了一些答案,其实完全不http://zend-framework-community.634137.n4.nabble.com/Setting-the-base-url-in-ZF2-MVC-td3946284.html工作。至于说hereStaticEventManager被弃用,所以我用SharedEventManager改变了它:

// In my Application\Module.php 

namespace Application; 
use Zend\EventManager\SharedEventManager 

    class Module { 
     public function init() {    

       $events = new SharedEventManager(); 
       $events->attach('bootstrap', 'bootstrap', array($this, 'registerBasePath')); 
      } 

      public function registerBasePath($e) { 

       $modules = $e->getParam('modules'); 
       $config = $modules->getMergedConfig(); 
       $app  = $e->getParam('application'); 
       $request = $app->getRequest(); 
       $request->setBasePath($config->base_path); 
      } 
     } 
    } 

在我modules/Application/configs/module.config.php我补充一下:

'base_path' => '/spam/ham/' 

但desn't工作。问题是:

1)运行永远不会进入registerBasePath函数。但它必须。我在init函数中附加了一个事件。

2)当我改变SharedEventManager只是EventManager碰巧来到registerBasePath功能,但一个exeption抛出:

Fatal error: Call to undefined method Zend\EventManager\EventManager::getParam() 

我该怎么办错了吗?为什么程序的运行没有进入registerBasePath函数?如果这是全球设置basePath的唯一方法,那么如何做到这一点?

回答

4

我知道文档缺乏这些东西。但是,你是正确的处理这个方式:

  1. 在早期(所以在系统启动)
  2. 抓斗从应用
  3. 设置基本路径的请求的请求

的文档缺乏这些信息,您提到的文章相当陈旧。这样做的最快和最简单的方法是使用onBootstrap()方法:

namespace MyModule; 

class Module 
{ 
    public function onBootstrap($e) 
    { 
     $app = $e->getApplication(); 
     $app->getRequest()->setBasePath('/foo/bar'); 
    } 
} 

如果你想抓住你的配置的基本路径,你可以加载有服务管理:

namespace MyModule; 

class Module 
{ 
    public function onBootstrap($e) 
    { 
     $app = $e->getApplication(); 
     $sm = $app->getServiceManager(); 

     $config = $sm->get('config'); 
     $path = $config->base_path; 

     $app->getRequest()->setBasePath($path); 
    } 
} 
+0

非常感谢你非常清楚的解释! – Green

相关问题