CodeIgniter получает весь список контроллеров с помощью своего метода

Я хочу создать роль пользователя и разрешение на основе метода контроллера. Для этого мне понадобился список контроллеров с его методом.

я хочу, чтобы это было динамически, если я добавлю метод в любой класс, чем он будет указан в этом списке

Для этого я попробовал это в своем методе. Но проблема в том, что он показывает только текущий контроллер и его метод.:

<?php
$controller = $this->router->fetch_class();
$method = $this->router->fetch_method();
?>

Пожалуйста помоги.

заранее спасибо


person Yogesh K    schedule 21.06.2016    source источник
comment
Просмотрите эту ссылку stackoverflow.com/questions/35177864/   -  person Yogesh Shakya    schedule 21.06.2016
comment
Спасибо @yogesh, это именно то, что я хочу.   -  person Yogesh K    schedule 21.06.2016
comment
Возможный дубликат Как получить массив всех контроллеров в проекте Codeigniter?   -  person Abdulla Nilam    schedule 21.06.2016


Ответы (1)


Используйте эту библиотеку, чтобы получить весь класс Codeigniter с вашими методами. В application/config/autoload.php вам нужно загрузить Controllerlist.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/***
 * File: (Codeigniterapp)/libraries/Controllerlist.php
 * 
 * A simple library to list all your controllers with their methods.
 * This library will return an array with controllers and methods
 * 
 * The library will scan the "controller" directory and (in case of) one (1) subdirectory level deep
 * for controllers
 * 
 * Usage in one of your controllers:
 * 
 * $this->load->library('controllerlist');
 * print_r($this->controllerlist->getControllers());
 * 
 * @author Peter Prins 
 */

class ControllerList {

    /**
     * Codeigniter reference 
     */
    private $CI;
    private $EXT;

    /**
     * Array that will hold the controller names and methods
     */
    private $aControllers;

    // Construct
    function __construct() {
        // Get Codeigniter instance 
        $this->CI = get_instance();
        $this->CI->EXT = ".php";

        // Get all controllers 
        $this->setControllers();
    }

    /**
     * Return all controllers and their methods
     * @return array
     */
    public function getControllers() {
        return $this->aControllers;
    }

    /**
     * Set the array holding the controller name and methods
     */
    public function setControllerMethods($p_sControllerName, $p_aControllerMethods) {
        $this->aControllers[$p_sControllerName] = $p_aControllerMethods;
    }

    /**
     * Search and set controller and methods.
     */
    private function setControllers() {
        // Loop through the controller directory
        foreach(glob(APPPATH . 'controllers/*') as $controller) {

            // if the value in the loop is a directory loop through that directory
            if(is_dir($controller)) {
                // Get name of directory
                $dirname = basename($controller, $this->CI->EXT);

                // Loop through the subdirectory
                foreach(glob(APPPATH . 'controllers/'.$dirname.'/*') as $subdircontroller) {
                    // Get the name of the subdir
                    $subdircontrollername = basename($subdircontroller, $this->CI->EXT);

                    // Load the controller file in memory if it's not load already
                    if(!class_exists($subdircontrollername)) {
                        $this->CI->load->file($subdircontroller);
                    }
                    // Add the controllername to the array with its methods
                    $aMethods = get_class_methods($subdircontrollername);
                    $aUserMethods = array();
                    foreach($aMethods as $method) {
                        if($method != '__construct' && $method != 'get_instance' && $method != $subdircontrollername) {
                            $aUserMethods[] = $method;
                        }
                    }
                    $this->setControllerMethods($subdircontrollername, $aUserMethods);                                      
                }
            }
            else if(pathinfo($controller, PATHINFO_EXTENSION) == "php"){
                // value is no directory get controller name                
                $controllername = basename($controller, $this->CI->EXT);

                // Load the class in memory (if it's not loaded already)
                if(!class_exists($controllername)) {
                    $this->CI->load->file($controller);
                }

                // Add controller and methods to the array
                $aMethods = get_class_methods($controllername);
                $aUserMethods = array();
                if(is_array($aMethods)){
                    foreach($aMethods as $method) {
                        if($method != '__construct' && $method != 'get_instance' && $method != $controllername) {
                            $aUserMethods[] = $method;
                        }
                    }
                }

                $this->setControllerMethods($controllername, $aUserMethods);                                
            }
        }   
    }
}
// EOF
person Marcos Vinicius    schedule 01.09.2018
comment
Спасибо за этот код. Это работает удивительно для моего проекта. Для своих целей я могу перечислить контроллеры как пользовательские приложения, а функции — как назначаемые инструменты. Мне нравится, что вы не включаете частные функции. Чтобы скрыть функции, я добавляю к ним набор символов, например «a_», и использую регулярное выражение, чтобы пропустить их. /^(index)|^\_|^([a-z]\_)/ - person DanimalReks; 29.09.2019