Codeigniter - url段替换或重定向

时间:2013-04-06 19:23:08

标签: codeigniter url redirect

我有一个所有其他控制器扩展的基本控制器(base)。 此处放置的任何内容都将覆盖其他控制器,重定向将在此处。

网址示例:

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

使用以下代码。会给我控制器名称

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

上述每个控制器都需要重定向到单独的URL,但功能部分不应更改:

 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类。

感谢。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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
} 

答案 2 :(得分: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...
}
相关问题