CodeIgniter - 如何动态获取所有控制器的列表?

时间:2015-06-09 05:48:52

标签: php codeigniter model-view-controller

我需要运行一个函数来对我的项目中的每个控制器名称执行一些操作。 我的函数在这样的控制器上定义:

class Some_Controller extends CI_Controller{
    public function someActions(){
        // $listOfAllControllers = some_method_I_need_for_my_answer();
        foreach($listOfAllControllers as $controllerName){
            // some_action($controllerName)
        }
    }
}

我想要的是项目中存在的所有控制器的动态列表

2 个答案:

答案 0 :(得分:3)

您需要扫描/application/controllers directory并从中删除文件扩展名

    $controllers = array();
    $this->load->helper('file');

    // Scan files in the /application/controllers directory
    // Set the second param to TRUE or remove it if you 
    // don't have controllers in sub directories
    $files = get_dir_file_info(APPPATH.'controllers', FALSE);

    // Loop through file names removing .php extension
    foreach ( array_keys($files) as $file ) {
        if ( $file != 'index.html' )
            $controllers[] = str_replace('.php', '', $file);
    }
    print_r($controllers); // Array with all our controllers

OR

您也可以点击此链接来实现此目标

controller list

答案 1 :(得分:1)

foreach(glob(APPPATH . 'controllers/*' . 'php') as $controller){
   $controller = basename($controller, '.php');
}