Autoloading file and it's class from certain location

I am doing this in a controller:

$menus = new submenus;

and it shows and error that it cannot load the file. How can i set the directory this certain file loads from?


Import (include) the class file before you use it, or put the class file in a directory that is in the include path. In Yii, you can do the above in one of the following ways:


// explicitly import the class

// this should be done at the beginning of the file 

// that references the class


// import the whole directory of protected/components

// anything under the directory will be autoloaded when needed

// NOTE: this is already done in the app config generated by "yiic webapp"


I have something tricky in that case i am trying to load a file named  menus.php and it is located under the directory: controllers/<controllerdirectory>/menus/menus.php

so for each controller there is a different file loaded with the same name but in a different directory. so i made a function in my base controller that looks like this:

public function LoadControllerMenus()




			$app = Yii::app()->controller->thisApplication;

			if(file_exists(Yii::app()->getControllerPath() . '/' . $app . '/menus/menus.php'))


				require_once(Yii::app()->getControllerPath() . '/' . $app . '/menus/menus.php');

				//$menus = new SubMenus;




if you notice it loads the menus.php file of the current active controller. how would i go on doing that so it will load the correct file based on the current loaded controller $app consists of the directory name of the current active controller


Because your file is not named after the class name, you won't be able to benefit from autoload. You can still use Yii::import though:

Yii::import('application.controllers.' . $this->id . '.menus.menus', true);

where $this refers to the current controller instance, and the 'true' parameter forces import to include the file (since it is not named after the class name).

Ahh thanks, will try this tomorrow.