How do I get an array of all controllers in a Codeigniter project?
I would like to get a list of all the controllers in the Codeiginiter project so that I can easily loop through each one and add specific routes. I can't seem to find a method that will give me what I want?
Here is a code snippet from routes.php file where I would like to access the array: -
// I'd like $controllers to be dynamically populated by a method
//
$controllers = array('pages', 'users');
// Loop through each controller and add controller/action routes
//
foreach ($controllers as $controller) {
$route[$controller] = $controller . '/index';
$route[$controller . '/(.+)'] = $controller . '/$1';
}
// Any URL that doesn't have a / in it should be tried as an action against
// the pages controller
//
$route['([^\/]+)$'] = 'pages/$1';
UPDATE # 1
To explain a little more of what I am trying to achieve. I have a page controller that contains pages like about, contact-us, privacy, etc. These pages should be accessible via / about, / contact-us, and / privacy. Thus, any action / method in the Pages controller must be available without specifying / pages / <action>.
Not sure if I'm going to do it right?
a source to share
To directly answer the question about coding, you can do this:
foreach(glob(APPPATH . 'controllers/*' . EXT) as $controller)
{
$controller = basename($controller, EXT);
$route[$controller] = $controller . '/index';
$route[$controller . '/(.+)'] = $controller . '/$1';
}
Buuuuuut this may not be the most flexible method further down the line.
There are several other ways to do this. One is to create MY_Router and insert
$this->set_class('pages');
$this->set_method($segments[0]);
before / instead of show_404 ();
This will send / link to / pages / contact, but only if no controllers, methods, routes are mapped first.
OOOOOOORRRRR use Modular separation and add the following to your main .php routes
$routes['404'] = 'pages';
a source to share