Does anyone have an idea on how to check if a controller exists based on a name? I’m working on a custom Url manager and I need to check first whether a route is a controller name (ie value is “site” > points to SiteController). So I’m trying to figure out a fast way to check if there is a SiteController class. I don’t think I could use class_exists() though because the controller class probably hasn’t been loaded yet. Right now I’m using CWebApplication::createController() which may not be a good idea.
function isControllerExists($id) //$id is controllerID eg)post,user
{
$i=ucfirst($id);
$controllerPath=Yii::app()->getControllerPath();
return file_exists($controllerPath.DIRECTORY_SEPARATOR.$i."Controller.php");//returns boolean
}
echo isControllerExists('user');//return 1 if there is UserController.php in controller folder.
Declare the following function in Controller.php (From which all the controllers are derived).
public function isControllerExists($id)
{
$id=ucfirst($id);
$controllerPath=($this->module==null)?Yii::app()->controllerPath:$this->module->controllerPath;
return file_exists($controllerPath.DIRECTORY_SEPARATOR.$id."Controller.php");
}
Now anywhere in your application
You can do it.
echo $this->isControllerExists("default");
If it is a module it looks into the controller folder inside the module.Else it looks into main application controller folder.