Wednesday, July 25, 2007

Quick Tip: Listing your CakePHP app controllers

Hi! When I started development on my latest CakePHP project, I wanted the homepage to print out a list of all available controllers in my application. Since I'm still in the beginning of development, a lot is bound to change so I don't want to manually have to update my navigation all the time.. Here's a quick and dirty solution for my problem:

// Read all PHP files in the controllers directory, return only the filenames
foreach(r(CONTROLLERS.'/', '', glob(CONTROLLERS.'/*.php')) as $file)
{
// Now convert the filename to a controller name
// Use a static call to Inflector:camelize() to convert the filename (minus _controller.php) to a
// camelized controller name.
$controller = Inflector::camelize(r('_controller.php', '', $file));
echo "\t". '.$controller."\n";
}
I use this in home.thtml, so I get a quick link list to all the controllers I have. You could also modify this and print it in your default.thtml template, so you can access every controller everywhere!