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

相關問題