热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Yii框架分析(一)——入口脚本index.php的启动过程剖析

Yii框架分析(一)——入口脚本index.php的启动过程剖析

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 数组中。

$this->preinit();
预初始化。preinit()是在 CModule 类里定义的,没有任何动作。

$this->initSystemHandlers() 方法内容:

/**
* Initializes the class autoloader and error handlers.
*/
protected function initSystemHandlers()
{
    if(YII_ENABLE_EXCEPTION_HANDLER)
        set_exception_handler(array($this,’handleException’));
    if(YII_ENABLE_ERROR_HANDLER)
        set_error_handler(array($this,’handleError’),error_reporting());
}

设置系统exception_handler和 error_handler,指向对象自身提供的两个方法。

4. 注册核心组件

$this->registerCoreComponents();
代码如下:

protected function registerCoreComponents()
{
    parent::registerCoreComponents();

    $components=array(
        ‘urlManager’=>array(
            ‘class’=>’CUrlManager’,
        ),
        ‘request’=>array(
            ‘class’=>’CHttpRequest’,
        ),
        ‘session’=>array(
            ‘class’=>’CHttpSession’,
        ),
        ‘assetManager’=>array(
            ‘class’=>’CAssetManager’,
         ),
        ‘user’=>array(
            ‘class’=>’CWebUser’,
         ),
        ‘themeManager’=>array(
            ‘class’=>’CThemeManager’,
        ),
        ‘authManager’=>array(
            ‘class’=>’CPhpAuthManager’,
        ),
        ‘clientScript’=>array(
            ‘class’=>’CClientScript’,
        ),
    );

    $this->setComponents($components);
}

注册了几个系统组件(Components)。
Components 是在 CModule 里定义和管理的,主要包括两个数组

private $_compOnents=array();
private $_compOnentConfig=array();

每个 Component 都是 IApplicationComponent接口的实例,Componemt的实例存放在$_components 数组里,相关的配置信息存放在$_componentConfig数组里。配置信息包括Component 的类名和属性设置。

CWebApplication 对象注册了以下几个Component:urlManager,request,session,assetManager,user,themeManager,authManager,clientScript。

CWebApplication的parent 注册了以下几个Component:coreMessages,db,messages,errorHandler,securityManager,statePersister。

Component 在YiiPHP里是个非常重要的东西,它的特征是可以通过 CModule 的 __get() 和 __set() 方法来访问。 Component 注册的时候并不会创建对象实例,而是在程序里被第一次访问到的时候,由CModule 来负责(实际上就是 Yii::app())创建。

5. 处理 $config 配置

继续, $this->configure($config);
configure() 还是在CModule 里:

public function configure($config)
{
    if(is_array($config))
    {
        foreach($config as $key=>$value)
            $this->$key=$value;
    }
}

实际上是把$config数组里的每一项传给 CModule 的 父类 CComponent __set() 方法。

public function __set($name,$value)
{
    $setter=’set’.$name;
    if(method_exists($this,$setter))
        $this->$setter($value);
    else if(strncasecmp($name,’on’,2)===0 && method_exists($this,$name))
    {
        //duplicating getEventHandlers() here for performance
        $name=strtolower($name);
        if(!isset($this->_e[$name]))
            $this->_e[$name]=new CList;
        $this->_e[$name]->add($value);
    }
    else if(method_exists($this,’get’.$name))
        throw new CException(Yii::t(‘yii’,'Property “{class}.{property}” is read only.’,
            array(‘{class}’=>get_class($this), ‘{property}’=>$name)));
    else
        throw new CException(Yii::t(‘yii’,'Property “{class}.{property}” is not defined.’,
            array(‘{class}’=>get_class($this), ‘{property}’=>$name)));
}

我们来看看:
if(method_exists($this,$setter))
根据这个条件,$config 数组里的basePath, params, modules, import, components 都被传递给相应的 setBasePath(), setParams() 等方法里进行处理。

6、$config 之 import

其中 import 被传递给 CModule 的 setImport:

public function setImport($aliases)
{
    foreach($aliases as $alias)
        Yii::import($alias);
}

Yii::import($alias)里的处理:

public static function import($alias,$forceInclude=false)
{
    // 先判断$alias是否存在于YiiBase::$_imports[] 中,已存在的直接return, 避免重复import。
    if(isset(self::$_imports[$alias])) // previously imported
        return self::$_imports[$alias];

    // $alias类已定义,记入$_imports[],直接返回
    if(class_exists($alias,false))
        return self::$_imports[$alias]=$alias;

    // 类似 urlManager 这样的已定义于$_coreClasses[]的类,或不含.的直接类名,记入$_imports[],直接返回
    if(isset(self::$_coreClasses[$alias]) || ($pos=strrpos($alias,’.'))===false) // a simple class name
    {
        self::$_imports[$alias]=$alias;
        if($forceInclude)
        {
            if(isset(self::$_coreClasses[$alias])) // a core class
                require(YII_PATH.self::$_coreClasses[$alias]);
            else
                require($alias.’.php’);
        }
        return $alias;
    }

    // 产生一个变量 $className,为$alias最后一个.后面的部分
    // 这样的:’x.y.ClassNamer’
    // $className不等于 ‘*’, 并且ClassNamer类已定义的,????? ClassNamer’ 记入 $_imports[],直接返回
    if(($className=(string)substr($alias,$pos+1))!==’*’ && class_exists($className,false))
        return self::$_imports[$alias]=$className;

    // 取得 $alias 里真实的路径部分并且路径有效
    if(($path=self::getPathOfAlias($alias))!==false)
    {
        // $className!==’*',$className 记入 $_imports[]
        if($className!==’*')
        {
            self::$_imports[$alias]=$className;
            if($forceInclude)
                require($path.’.php’);
            else
                self::$_classes[$className]=$path.’.php’;
            return $className;
        }
        // $alias是’system.web.*’这样的已*结尾的路径,将路径加到include_path中
        else // a directory
        {
            set_include_path(get_include_path().PATH_SEPARATOR.$path);
            return self::$_imports[$alias]=$path;
        }
    }
    else
        throw new CException(Yii::t(‘yii’,'Alias “{alias}” is invalid. Make sure it points to an existing directory or file.’,array(‘{alias}’=>$alias)));
}

7. $config 之 components

$config 数组里的 $components 被传递给CModule 的setComponents($components)

public function setComponents($components)
{
    foreach($components as $id=>$component)
    {
        if($component instanceof IApplicationComponent)
            $this->setComponent($id,$component);
        else if(isset($this->_componentConfig[$id]))
            $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
        else
            $this->_componentConfig[$id]=$component;
    }
}

$component是IApplicationComponen的实例的时候,直接赋值:
$this->setComponent($id,$component),

public function setComponent($id,$component)
{
    $this->_components[$id]=$component;
    if(!$component->getIsInitialized())
        $component->init();
}

如果$id已存在于_componentConfig[]中(前面注册的coreComponent),将$component 属性加进入。
其他的component将component属性存入_componentConfig[]中。

8. $config 之 params

这个很简单

public function setParams($value)
{
    $params=$this->getParams();
    foreach($value as $k=>$v)
        $params->add($k,$v);
}

configure 完毕!

9. attachBehaviors

$this->attachBehaviors($this->behaviors);
空的,没动作

预创建组件对象
$this->preloadComponents();

protected function preloadComponents()
{
    foreach($this->preload as $id)
        $this->getComponent($id);
}

getComponent() 判断_components[] 数组里是否有 $id的实例,如果没有,就根据_componentConfig[$id]里的配置来创建组件对象,调用组件的init()方法,然后存入_components[$id]中。

10. init()

$this->init();

函数内:$this->getRequest();
创建了Reques 组件并初始化。

11. run()

public function run()
{
    $this->onBeginRequest(new CEvent($this));
    $this->processRequest();
    $this->onEndRequest(new CEvent($this));
}

推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • Linuxchmod目录权限命令图文详解在Linux文件系统模型中,每个文件都有一组9个权限位用来控制谁能够读写和执行该文件的内容。对于目录来说,执行位的作用是控制能否进入或者通过 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • Lodop中特殊符号打印设计和预览样式不同的问题解析
    本文主要解析了在Lodop中使用特殊符号打印设计和预览样式不同的问题。由于调用的本机ie引擎版本可能不同,导致在不同浏览器下样式解析不同。同时,未指定文字字体和样式设置也会导致打印设计和预览的差异。文章提出了通过指定具体字体和样式来解决问题的方法,并强调了以打印预览和虚拟打印机测试为准。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • Final关键字的含义及用法详解
    本文详细介绍了Java中final关键字的含义和用法。final关键字可以修饰非抽象类、非抽象类成员方法和变量。final类不能被继承,final类中的方法默认是final的。final方法不能被子类的方法覆盖,但可以被继承。final成员变量表示常量,只能被赋值一次,赋值后值不再改变。文章还讨论了final类和final方法的应用场景,以及使用final方法的两个原因:锁定方法防止修改和提高执行效率。 ... [详细]
  • 本文介绍了求解gcdexgcd斐蜀定理的迭代法和递归法,并解释了exgcd的概念和应用。exgcd是指对于不完全为0的非负整数a和b,gcd(a,b)表示a和b的最大公约数,必然存在整数对x和y,使得gcd(a,b)=ax+by。此外,本文还给出了相应的代码示例。 ... [详细]
  • EPICS Archiver Appliance存储waveform记录的尝试及资源需求分析
    本文介绍了EPICS Archiver Appliance存储waveform记录的尝试过程,并分析了其所需的资源容量。通过解决错误提示和调整内存大小,成功存储了波形数据。然后,讨论了储存环逐束团信号的意义,以及通过记录多圈的束团信号进行参数分析的可能性。波形数据的存储需求巨大,每天需要近250G,一年需要90T。然而,储存环逐束团信号具有重要意义,可以揭示出每个束团的纵向振荡频率和模式。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • Microsoft Office for Mac最新版本安装教程,亲测可用!
    本文介绍了Microsoft Office for Mac最新版本的安装教程,经过亲测可用。Office工具是办公必备的工具,它为用户和企业设计,可以利用功能强大的Outlook处理电子邮件、日历和通讯录事宜。安装包包括Word、Excel、PPT、OneNote和Outlook。阅读本文可以了解如何下载并安装Office,以及安装过程中的注意事项。安装完毕后,可以正常使用Office中的Word等功能。 ... [详细]
  • 电销机器人作为一种人工智能技术载体,可以帮助企业提升电销效率并节省人工成本。然而,电销机器人市场缺乏统一的市场准入标准,产品品质良莠不齐。创业者在代理或购买电销机器人时应注意谨防用录音冒充真人语音通话以及宣传技术与实际效果不符的情况。选择电销机器人时需要考察公司资质和产品品质,尤其要关注语音识别率。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
author-avatar
芳方程_269
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有