用户
 找回密码
 入住 CI 中国社区
搜索
查看: 3785|回复: 0
收起左侧

[中级] CodeIgniter 源码分析之 Output.php

[复制链接]
发表于 2013-4-10 17:48:09 | 显示全部楼层 |阅读模式
原文: http://blog.163.com/wu_guoqing/b ... 701820128166414392/
作者: Calix

PHP复制代码
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
// ------------------------------------------------------------------------
 
/**
 * Output Class
 *
 * Output组件其实有很多有用的方法,不过一般情况下,你不会直接去用到它们。
 * 这里主要以Output::_display_cache()和Output::_display()为两条主线来探究。
 */

class CI_Output {
 
 /**
  * Current output string
  */

 protected $final_output;
 
 /**
  * Cache expiration time
  */

 protected $cache_expiration = 0;
 
 /**
  * List of server headers
  */

 protected $headers   = array();
 
 /**
  * List of mime types
  */

 protected $mime_types  = array();
 
 /**
  * Determines wether profiler is enabled
  */

 protected $enable_profiler = FALSE;
 
 /**
  * Determines if output compression is enabled
  * @access  protected
  */

 protected $_zlib_oc   = FALSE;
 
 /**
  * List of profiler sections
  */

 protected $_profiler_sections = array();
 
 /**
  * Whether or not to parse variables like {elapsed_time} and {memory_usage}
  */

 protected $parse_exec_vars = TRUE;
 
 /**
  * Constructor
  */

 function __construct()
 {
  $this->_zlib_oc = @ini_get('zlib.output_compression');
 
  if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
  {
      include APPPATH.'config/'.ENVIRONMENT.'/mimes.php';
  }
  else
  {
   include APPPATH.'config/mimes.php';
  }
 
 
  $this->mime_types = $mimes;
 
  log_message('debug', "Output Class Initialized");
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Get Output
  */

 function get_output()
 {
  //返回最终输出。
  return $this->final_output;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Set Output
  */

 function set_output($output)
 {
  //设置最终输出。
  $this->final_output = $output;
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Append Output
  */

 //通过此方法给Output::$final_output加上输出内容,最终这些内容会在Output::_display()中被输出。
 //此方法在Loader.php中被调用。详见Loader.php中的Loader::view()方法及Loader::_ci_load()方法。
 function append_output($output)
 {
  if ($this->final_output == '')
  {
   $this->final_output = $output;
  }
  else
  {
   $this->final_output .= $output;
  }
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Set Header
  */

 /**
  * 接下来的三个方法都是设置页面内容输出前的头信息。
  */

 function set_header($header, $replace = TRUE)
 {
  if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0)
  {
   return;
  }
 
  $this->headers[] = array($header, $replace);
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Set Content Type Header
  */

 function set_content_type($mime_type)
 {
  if (strpos($mime_type, '/') === FALSE)
  {
   $extension = ltrim($mime_type, '.');
 
   if (isset($this->mime_types[$extension]))
   {
    $mime_type =& $this->mime_types[$extension];
 
    if (is_array($mime_type))
    {
     $mime_type = current($mime_type);
    }
   }
  }
 
  $header = 'Content-Type: '.$mime_type;
 
  $this->headers[] = array($header, TRUE);
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Set HTTP Status Header
  */

 function set_status_header($code = 200, $text = '')
 {
  set_status_header($code, $text);
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Enable/disable Profiler
  */

 //是否开启评测器。
 function enable_profiler($val = TRUE)
 {
  $this->enable_profiler = (is_bool($val)) ? $val : TRUE;
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Set Profiler Sections
  */

 function set_profiler_sections($sections)
 {
  foreach ($sections as $section => $enable)
  {
   $this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE;
  }
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Set Cache
  */

 function cache($time)
 {
  //设置缓存时长。
  $this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time;
 
  return $this;
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Display Output
  */

 function _display($output = '')
 {
  //为什么这里要用global来调用这两个组件呢?不是可以通过$CI这个超级控制器来调用?
  //其实就是因为这个_display方法,被调用的方式有两种,其中有可能是在CodeIgniter.php中调用
  //Output::_display_cache();的时候间接被调用了,而此时& get_instance()这个方法压根还没
  //被定义。详见CodeIgniter.php中代码定义和调用的顺序。
  global $BM, $CFG;
 
  //当然如果可以拿到超级控制器,我们先拿过来。
  if (class_exists('CI_Controller'))
  {
   $CI =& get_instance();
  }
 
  // --------------------------------------------------------------------
 
  //如果$output为空,其实往往这是非缓存方式调用的时候。我们将使用Output::final_output。(如果是正常流程的输出
  //方式,而不是缓存的话,这个属性其实在Loader::view()的时候调用Output::append_output()获得输出内容。)
  if ($output == '')
  {
   $output =& $this->final_output;
  }
 
  // --------------------------------------------------------------------
 
  //Output::$cache_expiration其实就是缓存时长,就是平时我们在控制器里面$this->output->cache(n)设置的时长
  //现实手段就是使这个Output::$cache_expiration有一定的值,然后程序执行到这里时根据此值判断是否要缓存,
  //如果要缓存就生成缓存文件。(注意如果是_display_cache间接调用的话,$this->cache_expiraton是一定为0的,因为
  //没有经历过在控制器中调用$this->output->cache(n)。)
  if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
  {
   //上面有个判断$CI是否有_output方法,其实是提供一个机会让我们自定义处理输出。
   //生成缓存文件。
   $this->_write_cache($output);
  }
 
  // --------------------------------------------------------------------
 
  $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
 
  if ($this->parse_exec_vars === TRUE)
  {
   //系统的总体运行时间和内存消耗就是在这里替换的。呵呵。上面的Output::$parse_exec_vars就是设置要不要替换。
   $memory  = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB';
 
   $output = str_replace('{elapsed_time}', $elapsed, $output);
   $output = str_replace('{memory_usage}', $memory, $output);
  }
 
  // --------------------------------------------------------------------
  //压缩传输的处理。
  if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE)
  {
   if (extension_loaded('zlib'))
   {
    if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
    {
     ob_start('ob_gzhandler');
    }
   }
  }
 
  // --------------------------------------------------------------------
  if (count($this->headers) > 0)
  {
   foreach ($this->headers as $header)
   {
    @header($header[0], $header[1]);
   }
  }
 
  // --------------------------------------------------------------------
  //如果没有超级控制器,可以证明当前是在处理一个缓存的输出。不过利用这个方式来判断,真的有点那个。。。
  if ( ! isset($CI))
  {
   echo $output;//输出缓存内容。结束本函数。
   log_message('debug', "Final output sent to browser");
   log_message('debug', "Total execution time: ".$elapsed);
   return TRUE;
  }
 
  // --------------------------------------------------------------------
  //这里是一个评测器,如果有开启就调用,会生成一些报告到页面尾部用于辅助我们调试。我用CI的时候其实没有开启过,厄。
  if ($this->enable_profiler == TRUE)
  {
   $CI->load->library('profiler');
 
   if ( ! empty($this->_profiler_sections))
   {
    $CI->profiler->set_sections($this->_profiler_sections);
   }
 
   if (preg_match("|</body>.*?</html>|is", $output))
   {
    $output  = preg_replace("|</body>.*?</html>|is", '', $output);
    $output .= $CI->profiler->run();
    $output .= '</body></html>';
   }
   else
   {
    $output .= $CI->profiler->run();
   }
  }
 
  // --------------------------------------------------------------------
 
  //如果我们有在当前的控制器里面定义了_output这个方法,那么可以利用这个输出做你想做的东西,这个也是很不错的功能。
  if (method_exists($CI, '_output'))
  {
   $CI->_output($output);
  }
  else
  {
   //如果没有定义_output,就默认简单输出。
   echo $output;  // Send it to the browser!
  }
 
  log_message('debug', "Final output sent to browser");
  log_message('debug', "Total execution time: ".$elapsed);
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Write a Cache File
  */

 /**
  * 写入缓存。在Output::_display()中,判断需要缓存页面时,则调用此方法写入缓存。
  */

 function _write_cache($output)
 {
  //下面很多操作其实和读缓存的时候差不多。
 
  $CI =& get_instance();
  $path = $CI->config->item('cache_path');
 
  $cache_path = ($path == '') ? APPPATH.'cache/' : $path;
 
  if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
  {
   log_message('error', "Unable to write cache file: ".$cache_path);
   return;
  }
 
  $uri = $CI->config->item('base_url').
    $CI->config->item('index_page').
    $CI->uri->uri_string();
 
  $cache_path .= md5($uri);
 
  if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
  {
   log_message('error', "Unable to write cache file: ".$cache_path);
   return;
  }
 
  //计算缓存文件过期时间。
  $expire = time() + ($this->cache_expiration * 60);
 
  if (flock($fp, LOCK_EX))
  {
   //按CI的格式写入缓存内容。
   fwrite($fp, $expire.'TS--->'.$output);
   flock($fp, LOCK_UN);
  }
  else
  {
   log_message('error', "Unable to secure a file lock for file at: ".$cache_path);
   return;
  }
  fclose($fp);
  @chmod($cache_path, FILE_WRITE_MODE);
 
  log_message('debug', "Cache file written: ".$cache_path);
 }
 
 // --------------------------------------------------------------------
 
 /**
  * Update/serve a cached file
  */

 //在CodeIgniter.php里面有调用此方法,此方法是负责缓存的输出,如果在CodeIgniter.php中调用此方法有输出,则
 //本次请求的运行将直接结束,直接以缓存输出作为响应。
 function _display_cache(&$CFG, &$URI)
 {
  //取得保存缓存的路径
  $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');
 
  //一条准确的路由都会对应一个缓存文件,缓存文件是对应路由字符串的md5密文。
  $uri = $CFG->item('base_url').
    $CFG->item('index_page').
    $URI->uri_string;
 
  //计算出当前请求对应缓存文件的完整文件路径。
  $filepath = $cache_path.md5($uri);
 
  //如果没有此缓存文件,获取缓存内容失败,则可以返回FALSE。
  if ( ! @file_exists($filepath))
  {
   return FALSE;
  }
 
  //如果有此缓存文件,但是无法读,获取缓存内容失败,同样返回FALSE。
  if ( ! $fp = @fopen($filepath, FOPEN_READ))
  {
   return FALSE;
  }
 
  //打开到缓存文件,并以$fp作为句柄。下一步先取得共享锁(读取)。
  flock($fp, LOCK_SH);
 
  //读cache并保存到$cache中
  $cache = '';
  if (filesize($filepath) > 0)
  {
   $cache = fread($fp, filesize($filepath));
  }
 
  //解锁
  flock($fp, LOCK_UN);
  //关闭文件连接。
  fclose($fp);
 
  //下面这个TS--->字样,只是因为CI的缓存文件里面的内容是规定以数字+TS--->开头而已。这个数字是代表创建时间。
  //如果不符合此结构,可视为非CI的缓存文件,或者文件已损坏,获取缓存内容失败,返回FALSE。
  //如果匹配成功,则$match[1]中保存的是"1346901048TS--->"字样。其实在CI的这个版本$match[0]保存的是和
  //$match[1]相同的内容,为什么要分开?我觉得是为了以后扩展和方便改动吧,理解成
  //$match[0]是除页面内容之外的附加信息。
  //$match[1]是附加信息中和时间有关的信息。
  if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
  {
   return FALSE;
  }
 
  //去掉TS--->后,利用剩下的数字判断缓存是否已经过期,如果过期了,就把它删除,同样视为获取缓存内容失败(过期),
  //返回FALSE
  if (time() >= trim(str_replace('TS--->', '', $match['1'])))
  {
   if (is_really_writable($cache_path))
   {
    @unlink($filepath);
    log_message('debug', "Cache file has expired. File deleted");
    return FALSE;
   }
  }
 
  //来到这里,说明了能够顺利获得缓存,则去掉附加信息($match[0])后,调用Output::_display()方法输出缓存。并返回
  $this->_display(str_replace($match['0'], '', $cache));
  log_message('debug', "Cache file is current. Sending it to browser.");
  return TRUE;
 }
 
 
}
 
复制代码

本版积分规则