drr47973
drr47973
2018-08-01 03:39

Codeigniter路由错误涉及下划线

已采纳

I'm having a problem with Codeigniter routing which involves underscores in controller class names. Here's my problem and how to replicate it.

1) clone or download Codeigniter and save in a folder in htdocs called 'test'

git clone https://github.com/bcit-ci/CodeIgniter.git

2) create the following controller and save as C_track.php:

class C_track extends CI_Controller {
  public function index(){ echo "index done"; }
  public function demo(){ echo "demo done"; }
}

3) add the following route:

$route['track']= 'C_track';

4) Set 'base_url' within config.php correctly (for my setup, it's...):

$config['base_url'] = 'http://localhost:8888/test/';  

At this point, if I go to: http://localhost:8888/test/index.php/track/ I see: index done

but, if I go to: http://localhost:8888/test/index.php/track/demo I get a 404 error.

I am expecting to see: demo done

Ok, now things get strange

5)create the following controller and save as Track.php:

class Track extends CI_Controller {
  public function index(){ echo "index DONE!!!"; }
  public function demo(){ echo "demo DONE!!!"; }
}

6) Do not add a new route!

At this point, if I go to: http://localhost:8888/test/index.php/track/ I see: index done

but, if I go to: http://localhost:8888/test/index.php/track/demo I see: demo DONE!!!

This is not what I am expecting. For some reason, Codeigniter is running the demo function within Track.php, even though the file is not even listed in routes.php. I'm guessing that the underscore is the problem. because:

7) change routes.php:

$route['track']= 'Track';

Now, if I go to: http://localhost:8888/test/index.php/track/ I see: index DONE!!!

but, if I go to: http://localhost:8888/test/index.php/track/demo I see: demo DONE!!!

Which is exactly what I expect to see!!

How can I fix this? I would really like to find a way to solve this problem so that underscores work as expected, because my naming scheme is based heavily on underscores in file names & class names.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongming4994 dongming4994 3年前
    $route['track']= 'C_track';
    

    In a route, the array key contains the URI to be matched, while the array value contains the destination it should be re-routed to. In the above code, track is matched in the URI as final segment i.e. URI is delimited with / and broken into segmentssegment_description.

    For handling http://localhost:8888/test/index.php/track/demo use

    $route['track/(:any)']= 'C_track';
    

    The above will match 1 segment after track with any type of value and redirect it to the controller 'C_track'. Furthermore, the reason behind /track/demo working if you change the controller as Track.php is because when you rename the controller to Track.php, the URI matches with this controller by default without the need of adding a custom route in Routes.php.

    点赞 评论 复制链接分享

为你推荐