Codeigniter - routing to the controller if it exis

2019-02-26 01:30发布

问题:

So I have set up my routes like so:

$route[':any'] = "main";
$route['products/(:any)'] = "products/product/$1";

For example www.mysite.com/something goes to main controller, where I deal with "something". With products I deal in similar way.

But as you can see after that I have to write down all the other controllers with methods that I wish to be used instead of main controller. Is there a way to make it automatically detect if the controller exists use the controller and not the default "main"?

$route['products'] = "products";
$route['admin/user/login'] = "admin/user/login";
$route['admin/user/logout'] = "admin/user/logout";
$route['admin/migrations'] = "admin/migrations";
$route['admin/dashboard'] = "admin/dashboard";

回答1:

I can't take any credit for it as I found it on a blog somewhere, but I use the following code in my routes.php, in your case I would place it above the $route[':any'] = "main";

$controller_dir = opendir(APPPATH."controllers");

while (($file = readdir($controller_dir)) !== false) {

    if (substr($file, -4) == ".php" ) {

        $route[substr($file, 0, -4)."(.*)"] = substr($file, 0, -4)."$1";

    } elseif (substr($file, -5) == ".php/") {

        $route[substr($file, 0, -5)."(.*)"] = substr($file, 0, -5)."$1";

    }
}

Should I need to override any of them, or have any unique routes, I place those at the top of the routes.php file, above this code.