How to list all controller class name in codeigniter?
I want to create user authentication with access level for my site back end. I want get and list all contro开发者_StackOverflowller class name for create user group creation.
Thanks in advance,
Logan
Your best bet for this is to explicitly write them into a new config file.
$config['controllers'] = array(
'blog',
'events',
'news', // etc.
);
Otherwise, you will be scanning directories which will eat up resources. But you could do it like this:
$controllers = array();
$this->load->helper('file');
// Scan files in the /application/controllers directory
// Set the second param to TRUE or remove it if you
// don't have controllers in sub directories
$files = get_dir_file_info(APPPATH.'controllers', FALSE);
// Loop through file names removing .php extension
foreach (array_keys($files) as $file)
{
$controllers[] = str_replace(EXT, '', $file);
}
print_r($controllers); // Array with all our controllers
Since file names match controller names, now you should have an array of all your controllers. This isn't perfect though for several reasons, but should work for most setups.
Personally I use a highly modified directory structure, so this wouldn't work for me, and some controllers I would want to ignore as well. Another option would be to cache the results to a file, but that's a separate tutorial.
I highly suggest defining them in a config file, this way you can store other useful information directly related to your access control and avoid the huge overhead of recursively scanning directories.
Another way is to you could possibly do this is by creating an interface that you can then check for within your authentication system, for example, create a class like so:
interface IAuthorizationRequired
{
public function __auth();
}
Now create your controller (pseudo)
class BlogController extends CI_Controller implements IAuthorizationRequired
{
public function __auth()
{
/*Redirect or Custom*/
}
}
and within your authorization module, you load the current controller and do the follewing:
if(($controller instanceof IAuthorizationRequired) && method_exists(array($controller,'__auth')))
{
$authed = $controller->__auth();
if(!$authed)
{
echo 'Authorization Failed';
exit;
}
}
Within 2.0 you can override the base controller and add you method __auth to that, and then just check the interface, and run the auth.
精彩评论