开发者

How to get an array of all controllers in a Codeigniter project?

开发者 https://www.devze.com 2022-12-29 12:07 出处:网络
I\'d like to obtain a list of all controllers in a Codeiginiter project so I can easily loop through each of them and add defined routes.I can\'t seem to find a method that will give me what I\'m afte

I'd like to obtain a list of all controllers in a Codeiginiter project so I can easily loop through each of them and add defined routes. I can't seem to find a method that will give me what I'm after ?

Here is the code snippet from the 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 act开发者_开发百科ion against
// the pages controller
//
$route['([^\/]+)$'] = 'pages/$1';

UPDATE #1

To explain a little more what I'm trying to achieve.. I have a Pages controller which contains pages such as about, contact-us, privacy etc. These pages should all be accessible via /about, /contact-us and /privacy. So basically, any action/method in the Pages controller should be accessible without having to specify /pages/<action>.

Not sure if I'm going about this the right way ?


Well to directly answer to coding question, 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 work out to be the most flexible method further down the line.

There are a few other ways to do it. One is to create a MY_Router and insert

$this->set_class('pages'); 
$this->set_method($segments[0]);

before/instead of show_404();

That will send /contact to /pages/contact, but only if no controllers, methods, routes are mapped to first.

OOOOOOORRRRRR use Modular Separation and add the following to your main routes.php

$routes['404'] = 'pages';
0

精彩评论

暂无评论...
验证码 换一张
取 消