A naive but important question, please help

Dear friends,

I am puzzled by one question: why the model classes are available and accessible to all scripts in the application (that’s, available in controllers, in views, in custom application components, in widgets and portlets, and even in add-on modules) ?

Core components are available (e.g Yii::app()->component) because there are registered at application initiation. But those model classes are not registered. Right?

Please shed your light on me.

Thanks a lot !

Because Yii has autloader.

Look at protected/config/main.php , you’ll find such piece of code:

// autoloading model and component classes




models are imported to the autoload when you set in the config




everything you import will be added to the autoload’s search path

when you try to call a class that is not imported, autoload will search in those registered paths for the class file

you can import a folder or file at any time calling

Yii::import('application.components.*');//whole folder


Thanks to Layne and Gustavo,

i do find an autoload() in Yii class, it says:

"Class autoload loader. This method is provided to be invoked within an __autoload() magic method."

But i can’t find a __autoload() magic method in Yii or in CWebApplication.

Could you please explain a bit in details how this autoloading mechanism works?

its a php native function


Yii uses spl_autoload_register(). This makes possible to register more than one autoload functions, e.g. when a third-party library requires its own autoloader.