2016-12-02 28 views
3

我有一個SearchModule.php有以下幾點:getUrlRules - 開關控制器

class SearchModule extends CWebModule 
{  
    // function init() { } 
    /** 
    * @return array Правила роутинга для текущего модуля 
    */ 
    function getUrlRules() 
    { 
     $customController = (Yii::app()->theme->getName() == 'test' ? 'Test' : '') . '<controller>'; 

     return array(
      $this->id.'/<controller:\w+>/<action:(SupportBlock)>/<countryId:\d+>' => $this->id.'/' . $customController . '/<action>', 
      $this->id.'/<controller:\w+>/<action:(SupportBlock)>/<countryId:\d+>/<cityId:\d+>' => $this->id.'/' . $customController . '/<action>', 
      $this->id.'/visas' => $this->id.'/visas/fullVisasInfo', 
     ); 
    } 
} 

我試圖找出是如何使用另一個控制器,如果我的主題」設置爲‘測試’。現在它擁有名爲HotelsController或LocationsController的搜索控制器。我試圖實現的是,如果主題名稱設置爲「測試」,它應該將所有請求從同一網址路由到TestHotelsController或TestLocationsController(/ search/hotels應該路由到TestHotelsController而不是HotelsController)。

我已經試過通過在路由表的第二部分追加'測試'來做到這一點,但似乎沒有做任何事情。

回答

2

我已經找到一種方法,這種通過使用setControllerPath像這樣:

$customController = (Yii::app()->theme->getName() == 'test' ? 'test' : ''); 
$this->setControllerPath(__DIR__ ."/controllers/$customController"); 

在模塊的init()函數。這樣,自定義控制器的名稱保持不變,只有它的目錄發生更改。

2

您不會將關鍵字<controller>與任何類型的控制器名稱組合在一起。您可以給它一個自定義的唯一控制器名稱,或者使用<controller>關鍵字來讀取給定的控制器。和控制器名稱並不TestController,但它是TestHotelsController,這樣,試圖改變這樣的代碼:

function getUrlRules() 
{ 
    $customController = (Yii::app()->theme->getName() == 'test' ? 'hotelsTest' : 'hotels'); 

    if(strpos(Yii::app()->urlManager->parseUrl(Yii::app()->request), 'hotel')) { 
     $rules = array(
      $this->id . '/<controller:\w+>/<action:(SupportBlock)>/<countryId:\d+>' => $this->id . '/' . $customController . '/<action>', 
      $this->id . '/<controller:\w+>/<action:(SupportBlock)>/<countryId:\d+>/<cityId:\d+>' => $this->id . '/' . $customController . '/<action>', 
      $this->id . '/visas' => $this->id . '/visas/fullVisasInfo', 
     ); 
    } 
    else { 
     $rules = array(
      $this->id.'/<controller:\w+>/<action:(SupportBlock)>/<countryId:\d+>' => $this->id.'/<controller>/<action>', 
      $this->id.'/<controller:\w+>/<action:(SupportBlock)>/<countryId:\d+>/<cityId:\d+>' => $this->id.'/<controller>/<action>', 
      $this->id.'/visas' => $this->id.'/visas/fullVisasInfo', 
     ); 
    } 

    return $rules; 
} 
+0

這似乎並沒有訣竅,因爲它不會調用TestController的操作。我可以直接給他們打電話,但是通過這個路由,它一直呼叫標準HotelsController。我稍微修改了函數和控制器名稱,當我直接調用/ search/hotelsTest時,它會正確調用測試控制器的操作,但是它不會根據需要切換到調用它。 –