Tuesday, July 3, 2012

Using import and autoloading in YII Framework

When programming with PHP, one of the most annoying things is loading additional code with
include and require. Fortunately, you can do it automatically using the SPL class loader
(http://php.net/manual/en/function.spl-autoload.php).

Autoloading is one of the features which Yii relies on. Still, there are many questions about it
on the forums. Let's get it clear and show how we can use it.
When we are using a class, for example, CDbCriteria, we are not including it explicitly so
PHP initially cannot find it and is trying to rely on the autoloading feature; SPL autoloader
to be precise. In most cases, Yii default autoloader (YiiBase::autoload) will be used.
For the sake of speed and simplicity, almost all core framework classes are loaded when
needed without including or importing them explicitly. It's done through YiiBase::$_
coreClasses map, so loading core classes is very fast. Zii classes, such as CMenu,
extension classes or your own classes are not loaded automatically, so we need to import
them first.
To import classes, we will use Yii::import:
Import does not include a class immediately by default
It does not include a class if it is not used
It will not load a class twice, so it is safe to import the same class multiple times
Find more on http://Learnyii.ebharat.org

No comments:

Post a Comment