How do I list all the controllers/actions on my site? Configure::listObjects('model') doesnt seem to exist anymore. I am trying to write a function to generate/add to the ACO's in my ACL setup. Thanks.
Use $this->params['controller'] to get the current controller.
The controller as the name indicates controls the application. It acts like a bridge between models and views. Controllers handle request data, makes sure that correct models are called and right response or view is rendered. Methods in the controllers' class are called actions.
The loadModel() function comes handy when you need to use a model table/collection that is not the controller's default one: // In a controller method. $ this->loadModel('Articles'); $recentArticles = $this->Articles->find('all', [ 'limit' => 5, 'order' => 'Articles.created DESC' ]);
So here is what I did. In my Resource Controller:
Include the reflection class/method libraries
use ReflectionClass;
use ReflectionMethod;
To get the controllers:
public function getControllers() {
$files = scandir('../src/Controller/');
$results = [];
$ignoreList = [
'.',
'..',
'Component',
'AppController.php',
];
foreach($files as $file){
if(!in_array($file, $ignoreList)) {
$controller = explode('.', $file)[0];
array_push($results, str_replace('Controller', '', $controller));
}
}
return $results;
}
And now for the actions:
public function getActions($controllerName) {
$className = 'App\\Controller\\'.$controllerName.'Controller';
$class = new ReflectionClass($className);
$actions = $class->getMethods(ReflectionMethod::IS_PUBLIC);
$results = [$controllerName => []];
$ignoreList = ['beforeFilter', 'afterFilter', 'initialize'];
foreach($actions as $action){
if($action->class == $className && !in_array($action->name, $ignoreList)){
array_push($results[$controllerName], $action->name);
}
}
return $results;
}
Finally, to tie them boths together:
public function getResources(){
$controllers = $this->getControllers();
$resources = [];
foreach($controllers as $controller){
$actions = $this->getActions($controller);
array_push($resources, $actions);
}
return $resources;
}
I hope that helps some people.
It doesn't look like anything similar to this is still available in Cake3, nor is it still needed because of the namespaces I think.
So in short you can try to do this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With