2013-04-06 105 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 
}