1. 启动网站的唯一入口程序 index.php :
$yii=dirname(__FILE__).'/../framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
// remove the following line when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
require_once($yii);
Yii::createWebApplication($config)->run();
上面的require_once($yii) 引用出了后面要用到的全局类Yii,Yii类是YiiBase类的完全继承:
class Yii extends YiiBase{}
系统的全局访问都是通过Yii类(即YiiBase类)来实现的,Yii类的成员和方法都是static类型。
2. 类加载
Yii利用PHP5提供的spl库来完成类的自动加载。在YiiBase.php 文件结尾处
spl_autoload_register(array('YiiBase','autoload'));
将YiiBase类的静态方法autoload 注册为类加载器。 PHP autoload 的简单原理就是执行 new 创建对象或通过类名访问静态成员时,系统将 类名传递给被注册的类加载器函数,类加载器函数根据类名自行找到对应的类文件并include 。
下面是YiiBase类的autoload方法:
public static function autoload($className)
{
// use include so that the error PHP file may appear
if(isset(self::$_coreClasses[$className]))
include(YII_PATH.self::$_coreClasses[$className]);
else if(isset(self::$_classes[$className]))
include(self::$_classes[$className]);
else
include($className.'.php');
}
可以看到YiiBase的静态成员$_coreClasses 数组里预先存放着Yii系统自身用到的类对应的文件路径:
private static $_coreClasses=array(
'CApplication' => '/base/CApplication.php',
'CBehavior' => '/base/CBehavior.php',
'CComponent' => '/base/CComponent.php',
...
)
非 coreClasse 的类注册在YiiBase的$_classes 数组中:
private static $_classes=array();
其他的类需要用Yii::import()讲类路径导入PHP include paths 中,直接include($className.'.php')
3. CWebApplication的创建
回到前面的程序入口的 Yii::createWebApplication($config)->run();
public static function createWebApplication($config=null)
{
return new CWebApplication($config);
}
现在autoload机制开始工作了。
当系统 执行 new CWebApplication() 的时候,会自动include(YII_PATH.'/base/CApplication.php')将main.php里的配置信息数组$config传递给CWebApplication创建出对象,并执行对象的run() 方法启动框架。
CWebApplication类的继承关系
CWebApplication -> CApplication -> CModule -> CComponent
$config先被传递给CApplication的构造函数
public function __construct($config=null)
{
Yii::setApplication($this);
// set basePath at early as possible to avoid trouble
if(is_string($config))
$config=require($config);
if(isset($config['basePath']))
{
$this->setBasePath($config['basePath']);
unset($config['basePath']);
}
else
$this->setBasePath('protected');
Yii::setPathOfAlias('application',$this->getBasePath());
Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
$this->preinit();
$this->initSystemHandlers();
$this->registerCoreComponents();
$this->configure($config);
$this->attachBehaviors($this->behaviors);
$this->preloadComponents();
$this->init();
}
Yii::setApplication($this); 将自身的实例对象赋给Yii的静态成员$_app,以后可以通过 Yii::app() 来取得。后面一段是设置CApplication 对象的_basePath ,指向 proteced 目录。
Yii::setPathOfAlias('application',$this->getBasePath());
Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
设置了两个系统路径别名 application 和 webroot,后面再import的时候可以用别名来代替实际的完整路径。别名配置存放在YiiBase的 $_aliases 数组中。