At some point in time you may find the need to get a list of all of the controllers within your application. It's actually quite simple so long as you don't need controllers from any plugins.

Place this code in any of your controllers and view it from the web (for instance, from the Users Controller):

You'll see something similar to the following:

The App::objects() method returns an array of objects of the given type, such as: 'model', 'controller', 'helper', or 'plugin' - it also accepts other parameters, such as "path" in case you do eventually need to check controllers for your plugins.

The array_diff() is there as a much simpler method to remove the AppController and PagesController from the returned results as they would most likely exist in your application regardless and aren't normally something you'd need to worry about with ACL as there are other means within Cake to handle access to them. You'll notice that array_diff doesn't return an array starting at index of 0 since it removes keys from the original array too. That shouldn't be a problem, but if it is you can always use a loop instead of array_diff() and just unset or splice the matching values.

I used the CakePHP convenience method of pr() (print_r surrounded by PRE tags), and a die() simply to show the returned results and print them to the screen. You'd probably prefer to double underscore the function name (__listControllers()) to make it a private method to the class (rather than publicly viewable via the web), and change pr() to return.

What's the purpose of this?
- Maybe you'd want to create a web interface for ACL and need to know which controllers to give/deny access to/from
- Maybe you want to create a navigation menu based on your controllers
...maybe you can think of something that I can't. :)

Alter to your own tastes. This is only a starting point.

Other useful links (check version compatibility in these resources):
Quick dessert: List all controllers of a CakePHP application
Automatically load all controllers and actions into ACO tables for ACL with a CakePHP Task
How to list all controllers


Trackback specific URI for this entry
    No Trackbacks


    No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.

BBCode format allowed