码迷,mamicode.com
首页 > 其他好文 > 详细

Yii源码阅读笔记(二十六)

时间:2016-05-09 01:35:11      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

Application 类,是所有应用类的基类,注释了应用初始化时运行的一些方法:

  1 namespace yii\base;
  2 
  3 use Yii;
  4 
  5 /**
  6  * Application is the base class for all application classes.
  7  * Application 是所有应用类的基类
  8  *
  9  * @property \yii\web\AssetManager $assetManager The asset manager application component. This property is
 10  * read-only.
 11  * @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned
 12  * if auth manager is not configured. This property is read-only.
 13  * @property string $basePath The root directory of the application.
 14  * @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled.
 15  * This property is read-only.
 16  * @property \yii\db\Connection $db The database connection. This property is read-only.
 17  * @property \yii\web\ErrorHandler|\yii\console\ErrorHandler $errorHandler The error handler application
 18  * component. This property is read-only.
 19  * @property \yii\i18n\Formatter $formatter The formatter application component. This property is read-only.
 20  * @property \yii\i18n\I18N $i18n The internationalization application component. This property is read-only.
 21  * @property \yii\log\Dispatcher $log The log dispatcher application component. This property is read-only.
 22  * @property \yii\mail\MailerInterface $mailer The mailer application component. This property is read-only.
 23  * @property \yii\web\Request|\yii\console\Request $request The request component. This property is read-only.
 24  * @property \yii\web\Response|\yii\console\Response $response The response component. This property is
 25  * read-only.
 26  * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
 27  * subdirectory under [[basePath]].
 28  * @property \yii\base\Security $security The security application component. This property is read-only.
 29  * @property string $timeZone The time zone used by this application.
 30  * @property string $uniqueId The unique ID of the module. This property is read-only.
 31  * @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only.
 32  * @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under
 33  * [[basePath]].
 34  * @property View|\yii\web\View $view The view application component that is used to render various view
 35  * files. This property is read-only.
 36  *
 37  * @author Qiang Xue <qiang.xue@gmail.com>
 38  * @since 2.0
 39  */
 40 abstract class Application extends Module
 41 {
 42     /**
 43      * @event Event an event raised before the application starts to handle a request.
 44      * @event Event [[beforeRequest]]事件常量,处理请求前触发
 45      */
 46     const EVENT_BEFORE_REQUEST = ‘beforeRequest‘;
 47     /**
 48      * @event Event an event raised after the application successfully handles a request (before the response is sent out).
 49      * @event Event [[afterRequest]]事件常量,请求被成功处理后触发
 50      */
 51     const EVENT_AFTER_REQUEST = ‘afterRequest‘;
 52     /**
 53      * Application state used by [[state]]: application just started.
 54      * [[state]]属性使用,应用开始标记
 55      */
 56     const STATE_BEGIN = 0;
 57     /**
 58      * Application state used by [[state]]: application is initializing.
 59      * [[state]]属性使用,应用初始化标记
 60      */
 61     const STATE_INIT = 1;
 62     /**
 63      * Application state used by [[state]]: application is triggering [[EVENT_BEFORE_REQUEST]].
 64      * [[state]]属性使用,应用[[EVENT_BEFORE_REQUEST]]事件触发标记
 65      */
 66     const STATE_BEFORE_REQUEST = 2;
 67     /**
 68      * Application state used by [[state]]: application is handling the request.
 69      * [[state]]属性使用,应用处理请求标记
 70      */
 71     const STATE_HANDLING_REQUEST = 3;
 72     /**
 73      * Application state used by [[state]]: application is triggering [[EVENT_AFTER_REQUEST]].
 74      * [[state]]属性使用,应用触发[[EVENT_AFTER_REQUEST]]事件标记
 75      */
 76     const STATE_AFTER_REQUEST = 4;
 77     /**
 78      * Application state used by [[state]]: application is about to send response.
 79      * [[state]]属性使用,应用处理应答(返回值)标记
 80      */
 81     const STATE_SENDING_RESPONSE = 5;
 82     /**
 83      * Application state used by [[state]]: application has ended.
 84      * [[state]]属性使用,应用结束标记
 85      */
 86     const STATE_END = 6;
 87 
 88     /**
 89      * @var string the namespace that controller classes are located in.
 90      * @var string 控制器命名空间
 91      * This namespace will be used to load controller classes by prepending it to the controller class name.
 92      * 用于添加在控制器类名的前面加载控制器类,默认值为‘app\\controllers‘
 93      * The default namespace is `app\controllers`.
 94      *
 95      * Please refer to the [guide about class autoloading](guide:concept-autoloading.md) for more details.
 96      */
 97     public $controllerNamespace = ‘app\\controllers‘;
 98     /**
 99      * @var string the application name.
100      * @var string 应用名称
101      */
102     public $name = ‘My Application‘;
103     /**
104      * @var string the version of this application.
105      * @var string 应用版本号
106      */
107     public $version = ‘1.0‘;
108     /**
109      * @var string the charset currently used for the application.
110      *  @var string 默认的字符编码
111      */
112     public $charset = ‘UTF-8‘;
113     /**
114      * @var string the language that is meant to be used for end users. It is recommended that you
115      * @var string 显示给终端用户的语言,使用[IETF language tags]设定
116      * use [IETF language tags](http://en.wikipedia.org/wiki/IETF_language_tag). For example, `en` stands
117      * for English, while `en-US` stands for English (United States).
118      * @see sourceLanguage
119      */
120     public $language = ‘en-US‘;
121     /**
122      * @var string the language that the application is written in. This mainly refers to
123      * @var string 写入资源文件中的语言
124      * the language that the messages and view files are written in.
125      * @see language
126      */
127     public $sourceLanguage = ‘en-US‘;
128     /**
129      * @var Controller the currently active controller instance
130      *  @var Controller 默认活动的控制器实例
131      */
132     public $controller;
133     /**
134      * @var string|boolean the layout that should be applied for views in this application. Defaults to ‘main‘.
135      * @var string|boolean 布局文件对象
136      * If this is false, layout will be disabled.
137      */
138     public $layout = ‘main‘;
139     /**
140      * @var string the requested route
141      * @var string 请求路径
142      */
143     public $requestedRoute;
144     /**
145      * @var Action the requested Action. If null, it means the request cannot be resolved into an action.
146      * @var string 请求的方法
147      */
148     public $requestedAction;
149     /**
150      * @var array the parameters supplied to the requested action.
151      * @var array 请求参数
152      */
153     public $requestedParams;
154     /**
155      * @var array list of installed Yii extensions. Each array element represents a single extension
156      * with the following structure:
157      * @var array Yii extensions  Yii扩展列表
158      *
159      * ```php
160      * [
161      *     ‘name‘ => ‘extension name‘,
162      *     ‘version‘ => ‘version number‘,
163      *     ‘bootstrap‘ => ‘BootstrapClassName‘,  // optional, may also be a configuration array
164      *     ‘alias‘ => [
165      *         ‘@alias1‘ => ‘to/path1‘,
166      *         ‘@alias2‘ => ‘to/path2‘,
167      *     ],
168      * ]
169      * ```
170      *
171      * The "bootstrap" class listed above will be instantiated during the application
172      * [[bootstrap()|bootstrapping process]]. If the class implements [[BootstrapInterface]],
173      * its [[BootstrapInterface::bootstrap()|bootstrap()]] method will be also be called.
174      *
175      * If not set explicitly in the application config, this property will be populated with the contents of
176      * `@vendor/yiisoft/extensions.php`.
177      */
178     public $extensions;
179     /**
180      * @var array list of components that should be run during the application [[bootstrap()|bootstrapping process]].
181      * @var array 引导期间运行的的组件列表
182      *
183      * Each component may be specified in one of the following formats:
184      * 每一个组件的指定格式如下:
185      *
186      * - an application component ID as specified via [[components]].
187      *   组件的ID
188      * - a module ID as specified via [[modules]].
189      *   模块ID
190      * - a class name.
191      *   类名
192      * - a configuration array.
193      *   配置数组
194      *
195      * During the bootstrapping process, each component will be instantiated. If the component class
196      * implements [[BootstrapInterface]], its [[BootstrapInterface::bootstrap()|bootstrap()]] method
197      * will be also be called.
198      */
199     public $bootstrap = [];
200     /**
201      * @var integer the current application state during a request handling life cycle.
202      * This property is managed by the application. Do not modify this property.
203      * @var integer 默认的应用状态
204      */
205     public $state;
206     /**
207      * @var array list of loaded modules indexed by their class names.
208      * @var array 加载模块数组,可以通过模块名得到模块实例
209      */
210     public $loadedModules = [];
211 
212 
213     /**
214      * Constructor.
215      * 实例化应用的构造函数
216      * @param array $config name-value pairs that will be used to initialize the object properties.
217      * Note that the configuration must contain both [[id]] and [[basePath]].
218      * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
219      */
220     public function __construct($config = [])
221     {
222         Yii::$app = $this;//将\yii\base\Application里所有的公共方法都交给了,Yii::$app,其实Yii大部分信息都在Yii::$app变量中
223                           //当然也包括它的父类如:\yii\base\Module \yii\di\ServiceLocator \yii\base\Component \yii\base\Object
224         $this->setInstance($this);//这一句是指向\yii\base\Module,将\yii\base\Application中的所有的属性和方法交给Yii::$app->loadedModules数组中
225 
226         $this->state = self::STATE_BEGIN;//标记状态
227 
228         $this->preInit($config);//加载配置文件的框架信息 如:设置别名,设置框架路径等等 最为重要的是给加载默认组件
229 
230         $this->registerErrorHandler($config);//加载配置文件中的异常处理组件
231 
232         Component::__construct($config);//将配置文件中的所有信息赋值给Object,也就是Yii::$app->配置文件参数可以直接调用配置文件的内容 如:Yii::$app->vendorPath//输出框架路径  Yii::$app->components[‘redis‘]//输出redis配置信息
233     }
234 
235     /**
236      * Pre-initializes the application.
237      * 预初始化应用
238      * This method is called at the beginning of the application constructor.
239      * 该方法在构造函数中调用,用于初始化一些重要的属性
240      * It initializes several important application properties.
241      * If you override this method, please make sure you call the parent implementation.
242      * @param array $config the application configuration
243      * @param array $config 应用的配置
244      * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
245      */
246     public function preInit(&$config)
247     {
248         if (!isset($config[‘id‘])) {//判断配置中是否有application ID ,如果没有,抛出异常
249             throw new InvalidConfigException(‘The "id" configuration for the Application is required.‘);
250         }
251         if (isset($config[‘basePath‘])) {//判断配置中是否设置模块的basePath(即根路径)
252             $this->setBasePath($config[‘basePath‘]);//有则赋值给模块的_basepath属性,并在设置后,删除$config中的相应配置项
253             unset($config[‘basePath‘]);
254         } else {//否则抛出异常
255             throw new InvalidConfigException(‘The "basePath" configuration for the Application is required.‘);
256         }
257         // @vendor 如果配置文件中设置了 vendorPath 使用配置的值,并在设置后,删除$config中的相应配置项,否则使用默认的
258         if (isset($config[‘vendorPath‘])) {
259             $this->setVendorPath($config[‘vendorPath‘]);
260             unset($config[‘vendorPath‘]);
261         } else {
262             // set "@vendor"
263             $this->getVendorPath();
264         }
265         // @runtime 如果配置文件中设置了 runtimePath ,就使用配置的值,并在设置后,删除$config中的相应配置项,否则使用默认的
266         if (isset($config[‘runtimePath‘])) {
267             $this->setRuntimePath($config[‘runtimePath‘]);
268             unset($config[‘runtimePath‘]);
269         } else {
270             // set "@runtime"
271             $this->getRuntimePath();
272         }
273         // 设置timeZone(时区)属性,并在设置后,删除$config中的相应配置项
274         if (isset($config[‘timeZone‘])) {
275             $this->setTimeZone($config[‘timeZone‘]);
276             unset($config[‘timeZone‘]);
277         } elseif (!ini_get(‘date.timezone‘)) {
278             $this->setTimeZone(‘UTC‘);
279         }
280 
281         // merge core components with custom components
282          /**
283           * 将coreComponents() 所定义的核心组件配置,与开发者通过配置文件定义的组件配置进行合并
284           * 合并中,开发者配置优先,核心组件配置起补充作用。
285           */
286         foreach ($this->coreComponents() as $id => $component) {
287             if (!isset($config[‘components‘][$id])) {
288                 $config[‘components‘][$id] = $component;
289             } elseif (is_array($config[‘components‘][$id]) && !isset($config[‘components‘][$id][‘class‘])) {
290                 $config[‘components‘][$id][‘class‘] = $component[‘class‘];
291             }
292         }
293     }
294 
295     /**
296      * @inheritdoc
297      */
298     public function init()
299     {
300         $this->state = self::STATE_INIT;
301         $this->bootstrap();
302     }
303 
304     /**
305      * Initializes extensions and executes bootstrap components.
306      * 初始化扩展并执行初始化程序组件
307      * This method is called by [[init()]] after the application has been fully configured.
308      * 该方法在应用完全配置后被[[init()]]调用
309      * If you override this method, make sure you also call the parent implementation.
310      */
311     protected function bootstrap()
312     {
313         if ($this->extensions === null) {//如果扩展没有配置,则调用Yii的默认扩展组件
314             $file = Yii::getAlias(‘@vendor/yiisoft/extensions.php‘);
315             $this->extensions = is_file($file) ? include($file) : [];
316         }
317         foreach ($this->extensions as $extension) {//遍历扩展组件
318             if (!empty($extension[‘alias‘])) {//如果扩展组件有设置别名
319                 foreach ($extension[‘alias‘] as $name => $path) {
320                     Yii::setAlias($name, $path);//将给扩展的别名注册到别名数组中
321                 }
322             }
323             if (isset($extension[‘bootstrap‘])) {//如果扩展组件有[[bootstrap]]配置
324                 $component = Yii::createObject($extension[‘bootstrap‘]);//则初始化给扩展组件
325                 if ($component instanceof BootstrapInterface) {
326                     Yii::trace(‘Bootstrap with ‘ . get_class($component) . ‘::bootstrap()‘, __METHOD__);
327                     $component->bootstrap($this);
328                 } else {
329                     Yii::trace(‘Bootstrap with ‘ . get_class($component), __METHOD__);
330                 }
331             }
332         }
333 
334         foreach ($this->bootstrap as $class) {
335             $component = null;
336             if (is_string($class)) {
337                 if ($this->has($class)) {
338                     $component = $this->get($class);
339                 } elseif ($this->hasModule($class)) {
340                     $component = $this->getModule($class);
341                 } elseif (strpos($class, ‘\\‘) === false) {
342                     throw new InvalidConfigException("Unknown bootstrapping component ID: $class");
343                 }
344             }
345             if (!isset($component)) {
346                 $component = Yii::createObject($class);
347             }
348 
349             if ($component instanceof BootstrapInterface) {
350                 Yii::trace(‘Bootstrap with ‘ . get_class($component) . ‘::bootstrap()‘, __METHOD__);
351                 $component->bootstrap($this);
352             } else {
353                 Yii::trace(‘Bootstrap with ‘ . get_class($component), __METHOD__);
354             }
355         }
356     }
357 
358     /**
359      * Registers the errorHandler component as a PHP error handler.
360      * 注册errorHandler组件作为PHP错误处理函数
361      * @param array $config application config
362      */
363     protected function registerErrorHandler(&$config)
364     {
365         if (YII_ENABLE_ERROR_HANDLER) {//判断配置中是否启用Yii的错误处理程序组件
366             if (!isset($config[‘components‘][‘errorHandler‘][‘class‘])) {//配置中未定义错误处理程序组件,输出错误提示信息
367                 echo "Error: no errorHandler component is configured.\n";
368                 exit(1);
369             }
370             $this->set(‘errorHandler‘, $config[‘components‘][‘errorHandler‘]);//设置错误处理程序组件
371             unset($config[‘components‘][‘errorHandler‘]);//删除配置文件中的值
372             $this->getErrorHandler()->register();//返回组侧的错误处理程序
373         }
374     }
375 
376     /**
377      * Returns an ID that uniquely identifies this module among all modules within the current application.
378      * 返回当前应用的模块ID
379      * Since this is an application instance, it will always return an empty string.
380      * @return string the unique ID of the module.
381      */
382     public function getUniqueId()
383     {
384         return ‘‘;//因为这是一个应用实例,它将返回一个空字符串
385     }
386 
387     /**
388      * Sets the root directory of the application and the @app alias.
389      * 设置根路径和 @app 的别名
390      * This method can only be invoked at the beginning of the constructor.
391      * 该函数只能在构造函数中被调用
392      * @param string $path the root directory of the application.
393      * @property string the root directory of the application.
394      * @throws InvalidParamException if the directory does not exist.
395      */
396     public function setBasePath($path)
397     {
398         parent::setBasePath($path);
399         Yii::setAlias(‘@app‘, $this->getBasePath());
400     }
401 
402     /**
403      * Runs the application.
404      * 运行应用,该方法是应用的主入口
405      * This is the main entrance of an application.
406      * @return integer the exit status (0 means normal, non-zero values mean abnormal)
407      */
408     public function run()
409     {
410         try {
411 
412             $this->state = self::STATE_BEFORE_REQUEST;
413             $this->trigger(self::EVENT_BEFORE_REQUEST);//加载事件函数beforRequest函数
414 
415             $this->state = self::STATE_HANDLING_REQUEST;
416             $response = $this->handleRequest($this->getRequest());//加载控制器  //$this->getRequest()  //获取Request对象
417 
418             $this->state = self::STATE_AFTER_REQUEST;
419             $this->trigger(self::EVENT_AFTER_REQUEST);//加载afterRequest事件函数
420 
421             $this->state = self::STATE_SENDING_RESPONSE;
422             $response->send();//将页面内容输入缓冲,然后输出
423 
424             $this->state = self::STATE_END;
425 
426             return $response->exitStatus;
427 
428         } catch (ExitException $e) {
429 
430             $this->end($e->statusCode, isset($response) ? $response : null);
431             return $e->statusCode;
432 
433         }
434     }

 

Yii源码阅读笔记(二十六)

标签:

原文地址:http://www.cnblogs.com/isleep/p/5472335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!