2013-04-06 45 views
0

我有一個所有其他控制器擴展的基礎控制器(base)。 這裏放置的任何東西都會覆蓋其他控制器,重定向將在這裏。Codeigniter - url段替換或重定向

網址例如:

http://domain.com/controllerone/function 
http://domain.com/controllertwo/function 
http://domain.com/controllerthree/function 

使用下面的代碼。會給我控制器名稱

$this->uri->segment(1); 

上述每個控制器都需要被重定向到不同的網址,但funcation部分不應該改變:

http://domain.com/newcontrollerone/function 
http://domain.com/newcontrollertwo/function 
http://domain.com/newcontrollerthree/function 

在我的基本控制器我想下面的邏輯:

$controller_name = $this->uri->segment(1); 

    if($controller_name === 'controllerone'){ 
     // replace the controller name with new one and redirect, how ? 
    }else if($controller_name === 'controllertwo'){ 
    // replace the controller name with new one and redirect, how ? 
    }else{ 
     // continue as normal 
    } 

我想我應該用redirect()功能和str_replace(),但不知道如何有效這些將是。理想情況下,我不想使用Routing類。

謝謝。

回答

0

CodeIgniter's URI Routing,應該能夠在這種情況下提供幫助。但是,如果您有充分的理由不使用它,那麼此解決方案可能會有所幫助。

潛在重定向是在陣列中,其中所述是被查找的在URL控制器名稱和是控制器重定向到的名稱。這可能不是最有效率的,但我認爲它應該比潛在的非常長的if-then-else聲明更易於管理和閱讀。

//Get the controller name from the URL 
$controller_name = $this->uri->segment(1); 
//Alternative: $controller_name = $this->router->fetch_class(); 

//List of redirects 
$redirects = array(
    "controllerone" => "newcontrollerone", 
    "controllertwo" => "newcontrollertwo", 
    //...add more redirects here 
); 

//If a redirect exists for the controller  
if (array_key_exists($controller_name, $redirects)) 
{ 
    //Controller to redirect to 
    $redirect_controller = $redirects[$controller_name]; 
    //Create string to pass to redirect 
    $redirect_segments = '/' 
         . $redirect_controller 
         . substr($this->uri->uri_string(), strlen($controller_name)); //Function, parameters etc. to append (removes the original controller name) 
    redirect($redirect_segments, 'refresh');  
} 
else 
{ 
    //Do what you want... 
} 
+0

感謝您的回覆,如果這是'重定向($ redirect_url,'刷新');'>>'重定向($ redirect_segments,'刷新');'? – TheDeveloper 2013-04-07 13:18:46

+0

是的,應該是,對不起! – jleft 2013-04-07 13:25:30

+0

對我來說都很好,謝謝 – TheDeveloper 2013-04-08 18:39:23

1

嘗試

header("Location:".base_url("newcontroller/".$this->uri->segment(2))); 
+1

我認爲'重定向('newcontroller /'.$這個 - > URI->段(2));'將與笨更慣用的。 – complex857 2013-04-06 20:17:18

1

簡單的解決方案使用segment_array:

$segs = $this->uri->segment_array(); 

if($segs[1] === 'controllerone'){ 
    $segs[1] = "newcontroller"; 
    redirect($segs); 
}else if($segs[1] === 'controllertwo'){ 
    $segs[1] = "newcontroller2"; 
    redirect($segs); 
}else{ 
    // continue as normal 
}