简体   繁体   中英

How do I get a list of all functions inside a controller in cakephp

I needed to select a controller in CakePHP 2.4 and display all the functions written in it. I found how to list controllers from this question & answer thread on Stack Overflow but what I need now is given a specific controller I need to get the list of all functions it contains.

Here what i have done

public function getControllerList() {

   $controllerClasses = App::objects('controller');
   pr($controllerClasses);
   foreach($controllerClasses as $controller) { 

      $actions = get_class_methods($controller);
      echo '<br/>';echo '<br/>';
      pr($actions);

   }
}

pr($controllerClasses); gives me list of controllers as follows

Array
(
    [0] => AppController
    [1] => BoardsController
    [2] => TeamsController
    [3] => TypesController
    [4] => UsersController
)

however pr($actions); nothing... :(

here you go the final working snippet the way i needed

http://www.cleverweb.nl/cakephp/list-all-controllers-in-cakephp-2/

public function getControllerList() {

        $controllerClasses = App::objects('controller');
        foreach ($controllerClasses as $controller) {
            if ($controller != 'AppController') {
                // Load the controller
                App::import('Controller', str_replace('Controller', '', $controller));
                // Load its methods / actions
                $actionMethods = get_class_methods($controller);
                foreach ($actionMethods as $key => $method) {

                    if ($method{0} == '_') {
                        unset($actionMethods[$key]);
                    }
                }
                // Load the ApplicationController (if there is one)
                App::import('Controller', 'AppController');
                $parentActions = get_class_methods('AppController');
                $controllers[$controller] = array_diff($actionMethods, $parentActions);
            }
        }
        return $controllers;
    }

Something like this should do the trick: https://github.com/dereuromark/cakephp-sandbox/blob/master/Plugin/Sandbox/Controller/SandboxAppController.php#L12

It basically uses a very basic PHP function:

$actions = get_class_methods($Controller);

Then get parent methods:

$parentMethods = get_class_methods(get_parent_class($Controller));

Finally, using array_diff you get the actual actions in that controller:

$actions = array_diff($actions, $parentMethods);

Then you can still filter out unwanted actions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM