在CodeIgniter上默认重定向到控制器+操作的路由?

时间:2011-11-16 09:13:01

标签: codeigniter controller routes codeigniter-url

我目前正在与Codeigniter合作开展一个项目。

我有一个名为Cat的控制器

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 个答案:

答案 0 :(得分:2)

有几种方法可以做到这一点:

默认情况下,您可以使用'display'提供$ action:

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

您可能有条件进行物理重定向

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

你需要提供什么时候没有的路线:

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

此外,如果您在路线中只有特定数量的选项(例如'display','edit','new'),则可能值得设置您的路线:

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

编辑:

您创建的最后一条路线:

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

实际上是在控制器中查找function display()而不是将索引传递给'display'选项

答案 1 :(得分:0)

在控制器中使用_remap功能的最佳方法是将您的网址重新映射到控制器的特定方法

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