【问题标题】:Route to redirect to a controller + an action by default on CodeIgniter?在 CodeIgniter 上默认重定向到控制器 + 动作的路由?
【发布时间】:2011-12-30 06:04:12
【问题描述】:

我目前正在使用 Codeigniter 开展一个项目。

我有一个名为 Cat 的控制器

class Cat extends CI_Controller {

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

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

}

和一条路线(在 routes.php 中)

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

如果我使用这个 URL,例如:http://www.mywebsite.com/cats/display

但是,如果用户将 URL 更改为 http://www.mywebsite.com/cats/,它就不再起作用了。 Codeigniter 写道:404 Page Not Found - 找不到您请求的页面。

所以如果他在猫/页面上,我的目标是默认将他重定向到http://www.mywebsite.com/cats/display

我需要做另一条路线吗? 我试过了

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

...但没有成功。感谢您的帮助。

【问题讨论】:

    标签: codeigniter controller routes codeigniter-url


    【解决方案1】:

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

    您可以默认为 $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
    

    此外,如果您的路线中只有特定数量的选项(即“显示”、“编辑”、“新建”),则可能值得像这样设置您的路线:

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

    编辑:

    您创建的最后一条路线:

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

    实际上是在控制器中寻找function display(),而不是通过 index 'display' 选项

    【讨论】:

      【解决方案2】:

      在您的控制器中使用 _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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多