三)CodeIgniter源码分析之Common.php

  1 <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2 
  3 // ------------------------------------------------------------------------
  4 
  5 /**
  6  * Common Functions
  7  */
  8 
  9 /**
 10  * 为什么还要定义这些全局函数呢?比如说,下面有很多函数,如get_config()、config_item()这两个方法不是应该由
 11  * core/Config.php这个组件去做么?那个load_class()不应该由core/Loader.php去做么? 把这些函数定义出来貌似
 12  * 感觉架构变得不那么优雅,有点多余。
 13  * 其实是出于这样一种情况:
 14  * 比如说,如果一切和配置有关的动作都由Config组件来完成,一切加载的动作都由Loader来完成,
 15  * 试想一下,如果我要加载Config组件,那么,必须得通过Loader来加载,所以Loader必须比Config要更早实例化,
 16  * 但是如果Loader实例化的时候需要一些和Loader有关的配置信息才能实例化呢?那就必须通过Config来为它取得配置信息。
 17  * 这里就出现了鸡和鸡蛋的问题。。
 18  * 我之前写自己的框架也纠结过这样的问题,后来参考了YII框架,发现它里面其实都有同样的问题,它里面有个Exception的组件,
 19  * 但是在加载这个Exception组件之前,在加载其它组件的时候,如果出错了,那谁来处理异常和错误信息呢?答案就是先定义一些公共的函数。
 20  * 所以这些公共函数就很好地解决了这个问题,这也是为什么Common.php要很早被引入。
 21  * 
 22  */
 23 
 24 
 25 // ------------------------------------------------------------------------
 26 
 27 /**
 28 * Determines if the current version of PHP is greater then the supplied value
 29 */
 30 if ( ! function_exists('is_php'))
 31 {
 32  //判断当前php版本是不是$version以上的。调用version_compare()这个函数。
 33  function is_php($version = '5.0.0')
 34  {
 35   static $_is_php;
 36   $version = (string)$version;
 37 
 38   if ( ! isset($_is_php[$version]))
 39   {
 40    //PHP_VERION能够获得当前php版本。
 41    $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
 42   }
 43 
 44   return $_is_php[$version];
 45  }
 46 }
 47 
 48 // ------------------------------------------------------------------------
 49 
 50 /**
 51  * Tests for file writability
 52  */
 53 if ( ! function_exists('is_really_writable'))
 54 {
 55  //该函数和php官方手册上面写的差不多,兼容linux/Unix和windows系统:
 56  //http://www.php.net/manual/en/function.is-writable.php
 57  function is_really_writable($file)
 58  {
 59 
 60   //DIRECTORY_SEPARATOR是系统的目录分割符。利用它的值可以知道当前是不是linux系统。
 61   if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
 62   {
 63    //如果是linux系统的话,那么可以直接调用此方法来判断文件是否可写。
 64    return is_writable($file);
 65   }
 66 
 67   //如果是windows系统,则尝试写入一个文件来判断。
 68   
 69   if (is_dir($file))
 70   {
 71    //如果是目录,则创建一个随机命名的文件。
 72    $file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100));
 73 
 74    //如果文件不能创建,则返回不可写。
 75    if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
 76    {
 77     return FALSE;
 78    }
 79 
 80    fclose($fp);
 81    //删除刚才的文件。
 82    @chmod($file, DIR_WRITE_MODE);
 83    @unlink($file);
 84    return TRUE;
 85   }
 86   elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
 87   {
 88    //如果是一个文件,而通过写入方式打不开,则返回不可写。
 89    return FALSE;
 90   }
 91 
 92   fclose($fp);
 93   return TRUE;
 94  }
 95 }
 96 
 97 // ------------------------------------------------------------------------
 98 
 99 /**
100 * Class registry
101 */
102 if ( ! function_exists('load_class'))
103 {
104  //加载类。默认是加载libraries里面的,如果要加载核心组件,$directory就为'core'
105  function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
106  {
107   static $_classes = array();//用一个静态数组,保存已经加载过的类的实例,防止多次实例消耗资源,实现单例化。
108 
109   // Does the class exist?  If so, we're done...
110   if (isset($_classes[$class]))
111   {
112    return $_classes[$class];//如果已经保存在这里,就返回它。
113   }
114 
115   $name = FALSE;
116 
117   //这里,如果应用目录下有和系统目录下相同的类的话,优先引入应用目录,也就是你自己定义的。
118   foreach (array(APPPATH, BASEPATH) as $path)
119   {
120    if (file_exists($path.$directory.'/'.$class.'.php'))
121    {
122     $name = $prefix.$class;
123 
124     if (class_exists($name) === FALSE)
125     {
126      require($path.$directory.'/'.$class.'.php');
127     }
128 
129     break;
130    }
131   }
132 
133   //这里就用到的前缀扩展,如果在应用目录相应的目录下,有自己写的一些对CI库的扩展,那么我们加载的是它,而不是
134   //原来的。因为我们写的扩展是继承了CI原来的。
135   //所以可以看出,即使是CI的核心组件(core/下面的)我们都可以为之进行扩展。
136   if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
137   {
138    $name = config_item('subclass_prefix').$class;
139 
140    if (class_exists($name) === FALSE)
141    {
142     require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php');
143    }
144   }
145 
146   // Did we find the class?
147   if ($name === FALSE)
148   {
149    //这里用的是exit();来提示错误,而不是用show_error();这是因为这个load_class的错误有可能
150    //在加载Exception组件之前发。
151    exit('Unable to locate the specified class: '.$class.'.php');
152   }
153 
154   // Keep track of what we just loaded
155   //这个函数只是用来记录已经被加载过的类的类名而已。
156   is_loaded($class);
157 
158   $_classes[$class] = new $name();
159   return $_classes[$class];
160  }
161 }
162 
163 // --------------------------------------------------------------------
164 
165 /**
166 * Keeps track of which libraries have been loaded.  This function is
167 * called by the load_class() function above
168 */
169 if ( ! function_exists('is_loaded'))
170 {
171  //记录有哪些类是已经被加载的。
172  function is_loaded($class = '')
173  {
174   static $_is_loaded = array();
175 
176   if ($class != '')
177   {
178    $_is_loaded[strtolower($class)] = $class;
179   }
180 
181   return $_is_loaded;
182  }
183 }
184 
185 // ------------------------------------------------------------------------
186 
187 /**
188 * Loads the main config.php file
189 */
190 if ( ! function_exists('get_config'))
191 {
192  //这个是读取配置信息的函数,在Config类被实例化之前,由它暂负责。
193  //而在Config类被实例化之前,我们需要读取的配置信息,其实仅仅是config.php这个主配置文件的。所以这个方法是不能读出
194  //config/下其它配置文件的信息的。
195  //这个$replace参数,是提供一个临时替换配置信息的机会,仅一次,因为执行一次后,配置信息都会保存在静态变量$_config中,不能
196  //改变。
197  function &get_config($replace = array())
198  {
199   static $_config;
200 
201   if (isset($_config))
202   {
203    return $_config[0];
204   }
205 
206   // Is the config file in the environment folder?
207   if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php'))
208   {
209    $file_path = APPPATH.'config/config.php';
210   }
211 
212   // Fetch the config file
213   if ( ! file_exists($file_path))
214   {
215    exit('The configuration file does not exist.');
216   }
217 
218   require($file_path);
219 
220   // Does the $config array exist in the file?
221   if ( ! isset($config) OR ! is_array($config))
222   {
223    exit('Your config file does not appear to be formatted correctly.');
224   }
225 
226   // Are any values being dynamically replaced?
227   if (count($replace) > 0)
228   {
229    foreach ($replace as $key => $val)
230    {
231     if (isset($config[$key]))
232     {
233      $config[$key] = $val;
234     }
235    }
236   }
237 
238   return $_config[0] =& $config;
239  }
240 }
241 
242 // ------------------------------------------------------------------------
243 
244 /**
245 * Returns the specified config item
246 */
247 if ( ! function_exists('config_item'))
248 {
249  //取得配置数组中某个元素。
250  function config_item($item)
251  {
252   static $_config_item = array();
253 
254   if ( ! isset($_config_item[$item]))
255   {
256    $config =& get_config();
257 
258    if ( ! isset($config[$item]))
259    {
260     return FALSE;
261    }
262    $_config_item[$item] = $config[$item];
263   }
264 
265   return $_config_item[$item];
266  }
267 }
268 
269 // ------------------------------------------------------------------------
270 
271 /**
272 * Error Handler
273 */
274 
275 //这里的show_error和下面的show_404以及 _exception_handler这三个错误的处理,实质都是由Exception组件完成的。
276 //详见core/Exception.php.
277 if ( ! function_exists('show_error'))
278 {
279  
280  function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')
281  {
282   $_error =& load_class('Exceptions', 'core');
283   echo $_error->show_error($heading, $message, 'error_general', $status_code);
284   exit;
285  }
286 }
287 
288 // ------------------------------------------------------------------------
289 
290 /**
291 * 404 Page Handler
292 */
293 if ( ! function_exists('show_404'))
294 {
295 
296  function show_404($page = '', $log_error = TRUE)
297  {
298   $_error =& load_class('Exceptions', 'core');
299   $_error->show_404($page, $log_error);
300   exit;
301  }
302 }
303 
304 // ------------------------------------------------------------------------
305 
306 /**
307 * Error Logging Interface
308 */
309 if ( ! function_exists('log_message'))
310 {
311  function log_message($level = 'error', $message, $php_error = FALSE)
312  {
313   static $_log;
314 
315   if (config_item('log_threshold') == 0)
316   {
317    return;
318   }
319 
320   $_log =& load_class('Log');
321   $_log->write_log($level, $message, $php_error);
322  }
323 }
324 
325 // ------------------------------------------------------------------------
326 
327 /**
328  * Set HTTP Status Header
329  */
330 if ( ! function_exists('set_status_header'))
331 {
332  function set_status_header($code = 200, $text = '')
333  {
334   //此函数构造一个响应头。$stati为响应码与其响应说明。
335   $stati = array(
336        200 => 'OK',
337        201 => 'Created',
338        202 => 'Accepted',
339        203 => 'Non-Authoritative Information',
340        204 => 'No Content',
341        205 => 'Reset Content',
342        206 => 'Partial Content',
343 
344        300 => 'Multiple Choices',
345        301 => 'Moved Permanently',
346        302 => 'Found',
347        304 => 'Not Modified',
348        305 => 'Use Proxy',
349        307 => 'Temporary Redirect',
350 
351        400 => 'Bad Request',
352        401 => 'Unauthorized',
353        403 => 'Forbidden',
354        404 => 'Not Found',
355        405 => 'Method Not Allowed',
356        406 => 'Not Acceptable',
357        407 => 'Proxy Authentication Required',
358        408 => 'Request Timeout',
359        409 => 'Conflict',
360        410 => 'Gone',
361        411 => 'Length Required',
362        412 => 'Precondition Failed',
363        413 => 'Request Entity Too Large',
364        414 => 'Request-URI Too Long',
365        415 => 'Unsupported Media Type',
366        416 => 'Requested Range Not Satisfiable',
367        417 => 'Expectation Failed',
368 
369        500 => 'Internal Server Error',
370        501 => 'Not Implemented',
371        502 => 'Bad Gateway',
372        503 => 'Service Unavailable',
373        504 => 'Gateway Timeout',
374        505 => 'HTTP Version Not Supported'
375       );
376 
377   //如果调用此函数本身出错,则发出一个错误。
378   if ($code == '' OR ! is_numeric($code))
379   {
380    show_error('Status codes must be numeric', 500);
381   }
382 
383   if (isset($stati[$code]) AND $text == '')
384   {
385    $text = $stati[$code];
386   }
387   
388   //如果$text为空,一般是因为调用此函数时,给的响应码不正确同时又没有写出响应报文信息。
389   if ($text == '')
390   {
391    show_error('No status text available.  Please check your status code number or supply your own message text.', 500);
392   }
393 
394   //取得当前协议。
395   $server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE;
396 
397   //php_sapi_name()方法可以获得PHP与服务器之间的接口类型,

398   //下面是以cgi类型和以服务器模块形式类型的不同发出响应的方式。
399   if (substr(php_sapi_name(), 0, 3) == 'cgi')
400   {
401    header("Status: {$code} {$text}", TRUE);
402   }
403   elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0')
404   {
405    header($server_protocol." {$code} {$text}", TRUE, $code);
406   }
407   else
408   {
409    header("HTTP/1.1 {$code} {$text}", TRUE, $code);
410   }
411  }
412 }
413 
414 // --------------------------------------------------------------------
415 
416 /**
417 * Exception Handler
418 */
419 if ( ! function_exists('_exception_handler'))
420 {
421  //在CodeIgniter.php中执行set_error_handler('_exception_handler');后,以后一切非致命(非fatal)错误信息都由它处理。
422  //触发错误的时候,会产生几个参数,错误级别(号),错误信息,错误文件,错误行。
423  function _exception_handler($severity, $message, $filepath, $line)
424  {
425    /**
426     * 有关错误等级的内容可看:http://blog.163.com/wu_guoqing/blog/static/19653701820127269312682/
427     * E_STRICT对于大多数情况来说都是没多大作用的错误提示,这里CI把它屏蔽掉,如果实在要查看,可以查看日志文件。
428     */
429   if ($severity == E_STRICT)
430   {
431    return;
432   }
433 
434   //真正起到错误处理的是Exception组件。
435   $_error =& load_class('Exceptions', 'core');
436 
437   /*
438    * 注意下面的符号是&而不是&&,php的错误等级的值都是有规律的,例如1,2,4,8...(1,10,100,1000)等等,实际上,php是通过位运算来实现的,
439    * 使得错误控制更精准。(类似linux的权限控制,rwx)
440    * 在设置error_reporting()的时候,可通过E_XX|E_YY|E_ZZ的形式来设置,而判断的时候则通过E_XX&error_repoorting()来判断
441    * E_XX有没有设置。例如1,10,100,1000相或|,则值为1111,则以后1,10,100,1000中任意一个与1111相&,值都为它本身。
442    * 而E_ALL可以看到是除E_STRICT之外其它等级的“或(|)运算”。个人理解,之所以E_ALL的值是不同版本有所不同的,是
443    * 因为有时候会加入新的错误级别,从而导致这个E_ALL的值也不一样。
444    */
445   if (($severity & error_reporting()) == $severity)
446   {
447    //如果符合则交给Exception组件的show_php_error();进行处理。
448    $_error->show_php_error($severity, $message, $filepath, $line);
449   }
450 
451   //下面两行只是根据配置文件判断要不要log错误信息而已。
452   
453   if (config_item('log_threshold') == 0)
454   {
455    return;
456   }
457 
458   $_error->log_exception($severity, $message, $filepath, $line);
459  }
460 }
461 
462 // --------------------------------------------------------------------
463 
464 /**
465  * Remove Invisible Characters
466  */
467 if ( ! function_exists('remove_invisible_characters'))
468 {
469  function remove_invisible_characters($str, $url_encoded = TRUE)
470  {
471   $non_displayables = array();
472   
473   // every control character except newline (dec 10)
474   // carriage return (dec 13), and horizontal tab (dec 09)
475   
476   if ($url_encoded)
477   {
478    $non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
479    $non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
480   }
481   
482   $non_displayables[] = '/[x00-x08x0Bx0Cx0E-x1Fx7F]+/S'; // 00-08, 11, 12, 14-31, 127
483 
484   do
485   {
486    $str = preg_replace($non_displayables, '', $str, -1, $count);
487   }
488   while ($count);
489 
490   return $str;
491  }
492 }
493 
494 // ------------------------------------------------------------------------
495 
496 /**
497 * Returns HTML escaped variable
498 */
499 if ( ! function_exists('html_escape'))
500 {
501  function html_escape($var)
502  {
503   if (is_array($var))
504   {
505    return array_map('html_escape', $var);
506   }
507   else
508   {
509    return htmlspecialchars($var, ENT_QUOTES, config_item('charset'));
510   }
511  }
512 }
原文地址:https://www.cnblogs.com/qxbj/p/4415189.html