Quick dessert: List all controllers of a CakePHP application

Posted by Felix Geisendörfer, on Jul 12, 2007 - in PHP & CakePHP » Core & Hacking

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

Hi folks,

being busy as usual I don't have much time for blogging about the 'really' cool stuff. However here is a quick little dessert showing you how to get an array with all controllers in your application.

Update:: Thx to majna for pointing this out: The cake core has a function called listClasses() which can be used to find the controller files more quickly. Here is a new version making use of it:

php
  1. function listControllers() {
  2.     $Configure =& Configure::getInstance();
  3.     $controllers = array();
  4.     foreach($Configure->controllerPaths as $path) {
  5.         $controllers = am($controllers, array_map(array(&$this, '__controllerize'), listClasses($path)));
  6.     }
  7.    
  8.     return array_unique($controllers);
  9. }
  10.  
  11. function __controllerize($file) {
  12.     return Inflector::camelize(r('_controller.php', '', $file));
  13. }

I'll leave the old code around as well since even if it's less effective it still shows how one can use the Folder class:

php
  1. function listControllers() {
  2.     uses('Folder');
  3.     $Folder =& new Folder();
  4.  
  5.     $Configure =& Configure::getInstance();
  6.     $controllers = array();
  7.     foreach($Configure->controllerPaths as $path) {
  8.         $Folder->cd($path);
  9.         $controllerFiles = $Folder->find('.+_controller\.php$');
  10.         $controllers = am($controllers, array_map(array(&$this, '__controllerize'), $controllerFiles));
  11.     }
  12.    
  13.     return array_unique($controllers);
  14. }
  15.  
  16. function __controllerize($file) {
  17.     return Inflector::camelize(r('_controller.php', '', $file));
  18. }

It's something I've heard people asking for in IRC quite some times by now and since I just needed it again I thought I might as well publish it here. I hope somebody out there finds it useful.

-- Felix Geisendörfer aka the_undefined