Reputation: 153
I want to list all the modules , controllers and actions included in my project for acl purpose. But i dont know how can i fetch such information from zf2. Anyone has an idea of how to make this work? ThankYou :)
Upvotes: 3
Views: 2226
Reputation: 7238
You can get a array of the loaded modules from the ModuleManager
.
$moduleManager = $serviceManager->get('ModuleManager');
$loadedModules = $moduleManager->getLoadedModules();
For controllers you can retrieve them from the ControllerManager
.
$controllerManager = $this->getServiceLocator()->get('ControllerLoader');
foreach ($controllerManager->getCanonicalNames() as $alias) {
$controller = $controllerManager->get($alias); // This will get you the controller instance
}
ZF2 doesn't have any convenience methods built in to retrieve all the controller actions. Using some reflection would be your best bet imo.
$reflection = new \ReflectionClass($controller);
$actions = array();
foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
$methodName = $method->getName();
if ($methodName == 'getMethodFromAction') {
continue;
}
if (substr_compare($methodName, 'Action', -strlen('Action')) === 0) {
$actions[] = substr($methodName, 0, strlen($methodName) - 6);
}
}
var_dump($actions);
Upvotes: 2
Reputation: 691
Try this,
$manager = $this->getServiceLocator()->get('ModuleManager');
$modules = $manager->getLoadedModules();
$loadedModules = array_keys($modules);
$skipActionsList = array('notFoundAction', 'getMethodFromAction');
foreach ($loadedModules as $loadedModule) {
$moduleClass = '\\' .$loadedModule . '\Module';
$moduleObject = new $moduleClass;
$config = $moduleObject->getConfig();
$controllers = $config['controllers']['invokables'];
foreach ($controllers as $key => $moduleClass) {
$tmpArray = get_class_methods($moduleClass);
$controllerActions = array();
foreach ($tmpArray as $action) {
if (substr($action, strlen($action)-6) === 'Action' && !in_array($action, $skipActionsList)) {
$controllerActions[] = $action;
}
}
echo $loadedModule . "\n";
echo $moduleClass . "\n";
print_r($controllerActions);
}
}
Upvotes: 6