2011-11-16 102 views
2

我目前正在與Codeigniter一起開展一個項目。默認情況下,在CodeIgniter上重定向到控制器+操作的路由?

我稱之爲一個控制器貓

class Cat extends CI_Controller { 

    function __construct(){ 
     parent::__construct(); 
    } 

    function index($action){ 
     // code here 
    } 

} 

和路徑(在routes.php文件)

$route['cats/:any'] = 'cat/index/$1'; 

這工作,如果我使用這個網址,例如:http://www.mywebsite.com/cats/display

然而,如果用戶將URL更改爲http://www.mywebsite.com/cats/,則不再有效。 Codeigniter寫道:404未找到頁面 - 找不到您請求的頁面。

所以我的目標是在默認情況下,以他重定向到http://www.mywebsite.com/cats/display如果他是貓/頁

我需要做的另一條路線呢? 我試過

$route['cats'] = 'cat/display'; 

...但沒有成功。感謝您的幫助。

回答

2

有幾個方法可以做到這一點:

你可以在默認情況下爲$行動 '展示':

function index($action = 'display'){} 

OR

你可以有一個條件,物理重定向他們

function index($action = ''){ 
    if(empty($action)){redirect('/cats/display');} 
    //OTher Code 
} 

OR

您需要的時候有什麼也沒有提供路線:

$route['cats'] = 'cat/index/display'; //OR the next one 
$route['cats'] = 'cat/index'; //This requires an function similar to the second option above 

另外,如果你只在有你的路線(即選擇一個特定的編號。 '顯示器', '編輯', '新'),它可能是值得設置你的路線是這樣的:

$route['cats/([display|edit|new]+)'] = 'cat/index/$1'; 

編輯:

最後一條路由創建:

$route['cats'] = 'cat/display'; 

實際上是在控制器中尋找function display()而不是傳遞索引的「顯示」選項

+0

感謝您的答覆! – Dacobah

0

在你的程序中使用_remap函數的最好方法控制器將重新映射URL到特定的方法控制

class Cat extends CI_Controller { 

    function __construct(){ 
     parent::__construct(); 
    } 

    function _remap($action) 
    { 
     switch ($action) 
     { 
      case 'display': 
      $this->display(); 
      break; 
      default: 
       $this->index(); 
      break; 
     } 
    } 

    function index($action){ 
     // code here 
    } 

    function display(){ 
     echo "i will display"; 
    } 
    } 

check remap in CI user guide

相關問題