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

Yii分析1:web程序入口(3)

//第二个参数标识如果是空则创建之,默认为truepublicfunctiongetComponent($id,$createIfNull=true){if(isset($this->_components[$id]))return

接上篇:Yii分析1:web程序入口(2)

本文分析前两篇文章用到的一些函数。

 

上一篇提到在preloadComponents的时候会调用getComponent,我们来看一下getComponent的细节:

 

Yii_PATH/base/CModule.php

PHP
//第二个参数标识如果是空则创建之,默认为true public function getComponent($id,$createIfNull=true) { if(isset($this->_components[$id])) return $this->_components[$id]; //_componentConfig是在configure方法中由setComponents中已经保存的变量 else if(isset($this->_componentConfig[$id]) && $createIfNull) { $cOnfig=$this->_componentConfig[$id]; unset($this->_componentConfig[$id]); //如果没有设置enable参数或者enable参数为true if(!isset($config['enabled']) || $config['enabled']) { Yii::trace("Loading \"$id\" application component",'system.web.CModule'); unset($config['enabled']); //创建组件,并完成初始化 $compOnent=Yii::createComponent($config); $component->init(); return $this->_components[$id]=$component; } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
        //第二个参数标识如果是空则创建之,默认为true  
        public function getComponent($id,$createIfNull=true)  
        {  
            if(isset($this->_components[$id]))  
                return $this->_components[$id];          
            //_componentConfig是在configure方法中由setComponents中已经保存的变量  
            else if(isset($this->_componentConfig[$id]) && $createIfNull)  
            {  
                $cOnfig=$this->_componentConfig[$id];  
                unset($this->_componentConfig[$id]);  
                //如果没有设置enable参数或者enable参数为true  
                if(!isset($config['enabled']) || $config['enabled'])  
                {  
                    Yii::trace("Loading \"$id\" application component",'system.web.CModule');  
                    unset($config['enabled']);  
                    //创建组件,并完成初始化  
                    $compOnent=Yii::createComponent($config);  
                    $component->init();  
                    return $this->_components[$id]=$component;  
                }  
            }  
        }

 

下面是Yii::createComponent的实现:

PHP
public static function createComponent($config) { //如果配置项内容是一个字符串,则它是类名,如果是数组,那么数组的class成员是类名 if(is_string($config)) { $type=$config; $cOnfig=array(); } else if(isset($config['class'])) { $type=$config['class']; unset($config['class']); } else throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.')); //如果类不存在,则使用import来引入,而不是用autoload if(!class_exists($type,false)) $type=Yii::import($type,true); //创建组件时,可以带更多的初始值进行初始化 if(($n=func_num_args())>1) { $args=func_get_args(); if($n===2) $object=new $type($args[1]); else if($n===3) $object=new $type($args[1],$args[2]); else if($n===4) $object=new $type($args[1],$args[2],$args[3]); else { unset($args[0]); $class=new ReflectionClass($type); // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+ // $object=$class->newInstanceArgs($args); //如果参数大于4个,那么调用newInstance方法来进行初始化 $object=call_user_func_array(array($class,'newInstance'),$args); } } else $object=new $type; //将配置中的配置项赋值给组件的成员 foreach($config as $key=>$value) $object->$key=$value; return $object;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
        public static function createComponent($config)  
        {  
 
            //如果配置项内容是一个字符串,则它是类名,如果是数组,那么数组的class成员是类名  
            if(is_string($config))  
            {  
                $type=$config;  
                $cOnfig=array();  
            }  
            else if(isset($config['class']))  
            {  
                $type=$config['class'];  
                unset($config['class']);  
            }  
            else  
                throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));    
            //如果类不存在,则使用import来引入,而不是用autoload  
            if(!class_exists($type,false))  
                $type=Yii::import($type,true);    
 
            //创建组件时,可以带更多的初始值进行初始化  
            if(($n=func_num_args())>1)  
            {  
                $args=func_get_args();  
                if($n===2)  
                    $object=new $type($args[1]);  
                else if($n===3)  
                    $object=new $type($args[1],$args[2]);  
                else if($n===4)  
                    $object=new $type($args[1],$args[2],$args[3]);  
                else  
                {  
                    unset($args[0]);  
                    $class=new ReflectionClass($type);  
                    // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+  
                    // $object=$class->newInstanceArgs($args);  
                    //如果参数大于4个,那么调用newInstance方法来进行初始化  
                    $object=call_user_func_array(array($class,'newInstance'),$args);  
                }  
            }  
            else  
                $object=new $type;    
 
            //将配置中的配置项赋值给组件的成员  
            foreach($config as $key=>$value)  
                $object->$key=$value;  
 
            return $object;

 

=========================================================================

 

我们再来看看errorhandler和exceptionhandler:

 

Yii_PATH/base/CApplication.php

PHP
public function handleError($code,$message,$file,$line) { if($code & error_reporting()) { // disable error capturing to avoid recursive errors //恢复原错误handler(内建的错误handler),避免本函数触发错误handler,从而递归调用 restore_error_handler(); restore_exception_handler(); $log="$message ($file:$line)"; if(isset($_SERVER['REQUEST_URI'])) $log.=' REQUEST_URI='.$_SERVER['REQUEST_URI']; Yii::log($log,CLogger::LEVEL_ERROR,'php'); try { //使用一个error事件类来触发error事件,然后显示log信息,这里暂不分析 $event=new CErrorEvent($this,$code,$message,$file,$line); $this->onError($event); if(!$event->handled) { // try an error handler if(($handler=$this->getErrorHandler())!==null) $handler->handle($event); else $this->displayError($code,$message,$file,$line); } } catch(Exception $e) { $this->displayException($e); } $this->end(1); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
        public function handleError($code,$message,$file,$line)  
        {  
            if($code & error_reporting())  
            {  
                // disable error capturing to avoid recursive errors  
                //恢复原错误handler(内建的错误handler),避免本函数触发错误handler,从而递归调用  
                restore_error_handler();  
                restore_exception_handler();  
 
                $log="$message ($file:$line)";  
                if(isset($_SERVER['REQUEST_URI']))  
                    $log.=' REQUEST_URI='.$_SERVER['REQUEST_URI'];  
                Yii::log($log,CLogger::LEVEL_ERROR,'php');  
 
                try  
                {    
 
                    //使用一个error事件类来触发error事件,然后显示log信息,这里暂不分析  
                    $event=new CErrorEvent($this,$code,$message,$file,$line);  
                    $this->onError($event);  
                    if(!$event->handled)  
                    {  
                        // try an error handler  
                        if(($handler=$this->getErrorHandler())!==null)  
                            $handler->handle($event);  
                        else  
                            $this->displayError($code,$message,$file,$line);  
                    }  
                }  
                catch(Exception $e)  
                {  
                    $this->displayException($e);  
                }  
                $this->end(1);  
            }  
        }

dispalyError代码如下:

PHP
public function displayError($code,$message,$file,$line) { //如果是调试,打印调用栈,否则不打印 if(YII_DEBUG) { echo "PHP Error [$code]\n"; echo "

$message ($file:$line)

\n"; echo '
'; debug_print_backtrace(); echo '
'; } else { echo "PHP Error [$code]\n"; echo "

$message

\n"; } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    public function displayError($code,$message,$file,$line)                        
    {            
        //如果是调试,打印调用栈,否则不打印  
        if(YII_DEBUG)  
        {            
            echo "PHP Error [$code]\n";  
            echo "

$message ($file:$line)

\n";  
            echo '
';  
							
            debug_print_backtrace();  
            echo '';                                                          
        }                
        else  
        {                    
            echo "PHP Error [$code]\n";                                    
            echo "

$message

\n";                                              
        }        
    }

参考:

PHP
设定了error hanlder之后,某些级别的错误是不会触发设置的函数的,例如:E_ERROR(运行期错误,如内存分配错误),E_PARSE(解释错误,即语法),E_CORE_ERROR(在PHP内核startup阶段发生的错误),E_CORE_WARNING(在PHP内核startup阶段发生的warning),E_COMPILE_ERROR(编译错误,zend引擎生成),E_COMPILE_WARNING(编译warning,zend引擎生成) 关于startup和zend引擎请参考php内核方面的资料
1
2
3
设定了error hanlder之后,某些级别的错误是不会触发设置的函数的,例如:E_ERROR(运行期错误,如内存分配错误),E_PARSE(解释错误,即语法),E_CORE_ERROR(在PHP内核startup阶段发生的错误),E_CORE_WARNING(在PHP内核startup阶段发生的warning),E_COMPILE_ERROR(编译错误,zend引擎生成),E_COMPILE_WARNING(编译warning,zend引擎生成)  
 
关于startup和zend引擎请参考php内核方面的资料

handleException与Error相似:

PHP
public function handleException($exception) { // disable error capturing to avoid recursive errors restore_error_handler(); restore_exception_handler(); $category='exception.'.get_class($exception); //如果是Http异常,获取状态码 if($exception instanceof CHttpException) $category.='.'.$exception->statusCode; $message=(string)$exception; if(isset($_SERVER['REQUEST_URI'])) $message.=' REQUEST_URI='.$_SERVER['REQUEST_URI']; Yii::log($message,CLogger::LEVEL_ERROR,$category); //接下来同handleError try { $event=new CExceptionEvent($this,$exception); $this->onException($event); if(!$event->handled) { // try an error handler if(($handler=$this->getErrorHandler())!==null) $handler->handle($event); else $this->displayException($exception); } } catch(Exception $e) { $this->displayException($e); } $this->end(1); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
        public function handleException($exception)  
        {  
            // disable error capturing to avoid recursive errors  
            restore_error_handler();  
            restore_exception_handler();  
 
            $category='exception.'.get_class($exception);  
            //如果是Http异常,获取状态码  
            if($exception instanceof CHttpException)  
                $category.='.'.$exception->statusCode;  
            $message=(string)$exception;  
            if(isset($_SERVER['REQUEST_URI']))  
                $message.=' REQUEST_URI='.$_SERVER['REQUEST_URI'];  
            Yii::log($message,CLogger::LEVEL_ERROR,$category);  
 
            //接下来同handleError  
            try  
            {  
                $event=new CExceptionEvent($this,$exception);  
                $this->onException($event);  
                if(!$event->handled)  
                {  
                    // try an error handler  
                    if(($handler=$this->getErrorHandler())!==null)  
                        $handler->handle($event);  
                    else  
                        $this->displayException($exception);  
                }  
            }  
            catch(Exception $e)  
            {  
                $this->displayException($e);  
            }  
            $this->end(1);  
        }

参考:

PHP
call_user_function可以传递儿女和内置的或者用户自定义的函数,除了语言结构如array(), echo(), empty(), eval(), exit(), isset(), list(), print(), unset()
1
call_user_function可以传递儿女和内置的或者用户自定义的函数,除了语言结构如array(), echo(), empty(), eval(), exit(), isset(), list(), print(), unset()

推荐阅读
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • golang常用库:配置文件解析库/管理工具viper使用
    golang常用库:配置文件解析库管理工具-viper使用-一、viper简介viper配置管理解析库,是由大神SteveFrancia开发,他在google领导着golang的 ... [详细]
  • 深入解析JVM垃圾收集器
    本文基于《深入理解Java虚拟机:JVM高级特性与最佳实践》第二版,详细探讨了JVM中不同类型的垃圾收集器及其工作原理。通过介绍各种垃圾收集器的特性和应用场景,帮助读者更好地理解和优化JVM内存管理。 ... [详细]
  • 非公版RTX 3080显卡的革新与亮点
    本文深入探讨了图形显卡的进化历程,重点介绍了非公版RTX 3080显卡的技术特点和创新设计。 ... [详细]
  • Docker的安全基准
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • 程序员妻子吐槽:丈夫北漂8年终薪3万,存款情况令人意外
    一位程序员的妻子在网上分享了她丈夫在北京工作八年的经历,月薪仅3万元,存款情况却出乎意料。本文探讨了高学历人才在大城市的职场现状及生活压力。 ... [详细]
  • 本文详细介绍 Go+ 编程语言中的上下文处理机制,涵盖其基本概念、关键方法及应用场景。Go+ 是一门结合了 Go 的高效工程开发特性和 Python 数据科学功能的编程语言。 ... [详细]
  • Valve 发布 Steam Deck 的新版 Windows 驱动程序
    Valve 最新发布了针对 Steam Deck 掌机的 Windows 驱动程序,旨在提升其在 Windows 环境下的兼容性、安全性和性能表现。 ... [详细]
  • 本文详细介绍了 GWT 中 PopupPanel 类的 onKeyDownPreview 方法,提供了多个代码示例及应用场景,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • 本题探讨了一种字符串变换方法,旨在判断两个给定的字符串是否可以通过特定的字母替换和位置交换操作相互转换。核心在于找到这些变换中的不变量,从而确定转换的可能性。 ... [详细]
  • 在 Windows 10 中,F1 至 F12 键默认设置为快捷功能键。本文将介绍几种有效方法来禁用这些快捷键,并恢复其标准功能键的作用。请注意,部分笔记本电脑的快捷键可能无法完全关闭。 ... [详细]
  • 资源推荐 | TensorFlow官方中文教程助力英语非母语者学习
    来源:机器之心。本文详细介绍了TensorFlow官方提供的中文版教程和指南,帮助开发者更好地理解和应用这一强大的开源机器学习平台。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
author-avatar
melodyhaoduo
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有