egig
egig

Reputation: 4430

Load controller without $route

exmple: this load default controller/class with function page,

www.example.com/page

unless we have controller/class named page AND set $route['page'] = 'page'; it'll load the controller. But if we dont set the $route, it'll still load default_controller.

is that true a controller must have a $route[''] always? is not it possible to load controller page without set $route[''] even there is no default controller function with same name?

Edit:

I access

www.mysite.com/index.php/user

I do have user controller with index function, but my route file only contain:

$route['default_controller'] = 'page';
$route['(:any)'] = 'page/$1';
$route['product'] = 'product';
//$route['user'] = 'user';
$route['404_override'] = '';

returns 404, only works if I uncomment this: $route['user'] = 'user';

why?

Thanks.

Upvotes: 0

Views: 1834

Answers (1)

Aken Roberts
Aken Roberts

Reputation: 13467

No, that's not true. CodeIgniter, by default, directly maps URI segments to:

example.com/index.php/controller/method/param/param/...

Or if you have an .htaccess / similar solution to remove index.php:

example.com/controller/method/param/param/...

Routing is used when you wish to use a URL that does not directly map to this convention.

Edit: You have conflicting routes. CodeIgniter will look at each route in order from top to bottom, and if it find one that matches, it stops looking and processes that route. Because you have an (:any) catch-all route, it will match anything (like it says).

The rule of thumb is to place your most specific routes first, and then get more generic and catch-all later. Your (:any) route should be the very last one in your list. And the default controller and 404 overrides should stay first.

$route['default_controller'] = 'page';
$route['404_override'] = '';

$route['product'] = 'product';
$route['user'] = 'user';
$route['(:any)'] = 'page/$1';

You need to add the product and user routes because you've defined the (:any) route. If you want to avoid writing route rules for every one of your existing controllers, but still take advantage of a catch-all controller, consider using the 404_override controller/method instead. You can do your verifications to check if the URI is valid there. Just make sure to throw a 404 error if not (you can use show_404()), since any non-existant URL will be routed to there.

Upvotes: 2

Related Questions