How to get list of all controllers and models


#1

Hi there,

Does anybody know a simple way of how to get a list of all controllers and models in CakePHP version 3.7?

I hope someone can help.

Thanks


#2

ls src/Controllers?

Do you mean programmatically from within your application? I don’t think there is anything built-in to do that. You could get the list of tables from the database schema, but that’s not necessarily going to be a 1-to-1 match for your list of controllers and/or models. When I’ve needed to do similar things, I end up just iterating over the files matching a glob pattern in the particular folder.


#3

Yes, I mean programmatically. I have done that before using earlier versions of Cakephp. I have been looking around and it looks like I am going to have to use the Cake’s built-in Folder and File classes to do the job. I will write a function to do that. Might share the code for others to use if they need it as well.

Thanks for the input.


#4

Ok,

I am using CakePHP version 3.7.
I have now wrote some simple code to get the list of all controllers. I am sharing it in case someone else finds it useful etc. See: https://book.cakephp.org/3.0/en/core-libraries/file-folder.html

In src\Controller, open AppController.php and include the following:

use \Cake\Filesystem\Folder;
use \Cake\Filesystem\File;

The two simple functions I wrote to do the job:

public function getControllers()
{
$folder = new Folder(ROOT);
$controllerFiles = $folder->cd(‘src’.DS.‘Controller’);
$controllerFiles = $folder->find(’.*.php’, true);

	$skipControllers = ['AppController.php'];
	$cleanControllers = [];
	foreach ($controllerFiles as $key => $controller) {
		
		if (!in_array($controller, $skipControllers)) {
			$cleanControllers[] = str_replace('Controller.php','',$controller);
			//Could build a menu based on the controller here now, but do not
			//have time to do this now.
		}
	}
	
	return $cleanControllers;
}

public function setControllers ()
{
	$this->set('all_controllers', $this->getControllers());
}

You can then call: $this->setControllers(); in the beforeRender function of your AppController to make the controllers array available in the view / template etc.

I hope someone finds this useful.


#5

Might want to find .*Controller.php, in case you have any non-controller files in there? I know, there shouldn’t really be, but maybe something like a trait that only controllers could ever use? Or a declaration of an interface that some of your controllers conform to? Perhaps would apply more to finding all the models than all the controllers.


#6

Check this stackoverflow post as well for controllers and actions: