CodeIgniter Output.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package CodeIgniter
 * @author ExpressionEngine Dev Team
 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license http://codeigniter.com/user_guide/license.html
 * @link http://codeigniter.com
 * @since Version 1.0
 * @filesource
 */


// ------------------------------------------------------------------------


/**
 * Output Class
 *
 * Responsible for sending final output to browser
 *
 * @package CodeIgniter
 * @subpackage Libraries
 * @category Output
 * @author ExpressionEngine Dev Team
 * @link http://codeigniter.com/user_guide/libraries/output.html
 */
class CI_Output {


/**
* Current output string
*
* @var string
* @access protected
*/
//输出字符串
protected $final_output;
/**
* Cache expiration time
*
* @var int
* @access protected
*/
//缓存的有效期
protected $cache_expiration = 0;
/**
* List of server headers
*
* @var array
* @access protected
*/
//头信息
protected $headers = array();
/**
* List of mime types
*
* @var array
* @access protected
*/
protected $mime_types = array();
/**
* Determines wether profiler is enabled
*
* @var book
* @access protected
*/
//评测器是否可用
protected $enable_profiler = FALSE;
/**
* Determines if output compression is enabled
*
* @var bool
* @access protected
*/
//是否压缩输出
protected $_zlib_oc = FALSE;
/**
* List of profiler sections
*
* @var array
* @access protected
*/
//列出可选的评测器
protected $_profiler_sections = array();
/**
* Whether or not to parse variables like {elapsed_time} and {memory_usage}
*
* @var bool
* @access protected
*/
//CodeIgniter总会在输出中解析伪变量{elapsed_time}和{memory_usage}。 
//如需禁用,在控制器中将类属性$parse_exec_vars设为FALSE。
protected $parse_exec_vars = TRUE;
/**
* Constructor
*
*/
//加载一些配置信息
function __construct()
{
//ini_get()获取php.ini配置选项的值
$this->_zlib_oc = @ini_get('zlib.output_compression');

//引入mimes.php文件
// Get mime types for later
if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
   include APPPATH.'config/'.ENVIRONMENT.'/mimes.php';
}
else
{
include APPPATH.'config/mimes.php';
}


//mimes类型
$this->mime_types = $mimes;


log_message('debug', "Output Class Initialized");
}


// --------------------------------------------------------------------


/**
* Get Output
*
* Returns the current output string
*
* @access public
* @return string
*/
//使用这个方法,你可以得到将要输出的数据,并把它保存起来,
//留着它用(我们做新闻类型网站的时候,常常需要生成静态的HTML文件)
function get_output()
{
return $this->final_output;
}


// --------------------------------------------------------------------


/**
* Set Output
*
* Sets the output string
*
* @access public
* @param string
* @return void
*/
//告诉CodeIgniter方法执行完毕后,用给定的数据做为输出
//重要:使用这个方法有一点很重要,就要将它放在最后一句,千万要注意啊,到时候出了错,不要怪我没提醒你.
function set_output($output)
{
$this->final_output = $output;


return $this;
}


// --------------------------------------------------------------------


/**
* Append Output
*
* Appends data onto the output string
*
* @access public
* @param string
* @return void
*/
//在输出字符串后附加数据。
//通过此方法给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
*
* Lets you set a server header which will be outputted with the final display.
*
* Note:  If a file is cached, headers will not be sent.  We need to figure out
* how to permit header data to be saved with the cache data...
*
* @access public
* @param string
* @param bool
* @return void
*/
//使用此方法,允许你设置将会被发送到浏览器的HTTP协议的标头,作用相当于php的标准函数: header()。
function set_header($header, $replace = TRUE)
{
// If zlib.output_compression is enabled it will compress the output,
// but it will not modify the content-length header to compensate for
// the reduction, causing the browser to hang waiting for more data.
// We'll just skip content-length in those cases.
//strncasecmp()二进制安全比较字符串开头的若干个字符(不区分大小写)
if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0)
{
return;
}


$this->headers[] = array($header, $replace);


return $this;
}


// --------------------------------------------------------------------


/**
* Set Content Type Header
*
* @access public
* @param string extension of the file we're outputting
* @return void
*/
//允许你设置页面的mime类型以便于输出 JSON , JPEG, XML 等类型的数据.
//重要: 确保你传递到此方法的非mime字符串在 config/mimes.php 存在,否则设置不起作用。
function set_content_type($mime_type)
{
if (strpos($mime_type, '/') === FALSE)
{
$extension = ltrim($mime_type, '.');


// Is this extension supported?
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
* moved to Common procedural functions in 1.7.2
*
* @access public
* @param int the status code
* @param string
* @return void
*/
//允许你手动设置服务器状态头(header)。
function set_status_header($code = 200, $text = '')
{
set_status_header($code, $text);


return $this;
}


// --------------------------------------------------------------------


/**
* Enable/disable Profiler
*
* @access public
* @param bool
* @return void
*/
//允许你开启或禁用评测器,评测器将在页的底部显示测试基准点或调试、优化需要的其他数据。
//在控制器函数的任何位置放置以下函数,可以开启评测器:
//$this->output->enable_profiler(TRUE);
//当开启评测器功能,会在您的页面底部生成一个报告。
function enable_profiler($val = TRUE)
{
$this->enable_profiler = (is_bool($val)) ? $val : TRUE;


return $this;
}


// --------------------------------------------------------------------


/**
* Set Profiler Sections
*
* Allows override of default / config settings for Profiler section display
*
* @access public
* @param array
* @return void
*/
//允许你在评测器启用时控制(开/关)其特定部分
function set_profiler_sections($sections)
{
foreach ($sections as $section => $enable)
{
$this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE;
}


return $this;
}


// --------------------------------------------------------------------


/**
* Set Cache
*
* @access public
* @param integer
* @return void
*/
//CodeIgniter的输出类同样也控制缓存
function cache($time)
{
$this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time;


return $this;
}


// --------------------------------------------------------------------


/**
* Display Output
*
* All "view" data is automatically put into this variable by the controller class:
*
* $this->final_output
*
* This function sends the finalized output data to the browser along
* with any server headers and profile data.  It also stops the
* benchmark timer so the page rendering speed and memory usage can be shown.
*
* @access public
* @param string
* @return mixed
*/
function _display($output = '')
{
// Note:  We use globals because we can't use $CI =& get_instance()
// since this function is sometimes called by the caching mechanism,
// which happens before the CI super object is available.
  //为什么这里要用global来调用这两个组件呢?不是可以通过$CI这个超级控制器来调用?
  //其实就是因为这个_display方法,被调用的方式有两种,其中有可能是在CodeIgniter.php中调用
  //Output::_display_cache();的时候间接被调用了,而此时& get_instance()这个方法压根还没
  //被定义。详见CodeIgniter.php中代码定义和调用的顺序。
global $BM, $CFG;
//当然如果可以拿到超级控制器,我们先拿过来。
// Grab the super object if we can.
if (class_exists('CI_Controller'))
{
$CI =& get_instance();
}


// --------------------------------------------------------------------
//如果$output为空,其实往往这是非缓存方式调用的时候。我们将使用Output::final_output。(如果是正常流程的输出
  //方式,而不是缓存的话,这个属性其实在Loader::view()的时候调用Output::append_output()获得输出内容。)
// Set the output data
if ($output == '')
{
$output =& $this->final_output;
}


// --------------------------------------------------------------------


// Do we need to write a cache file?  Only if the controller does not have its
// own _output() method and we are not dealing with a cache file, which we
// can determine by the existence of the $CI object above
//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);
}


// --------------------------------------------------------------------


// Parse out the elapsed time and memory usage,
// then swap the pseudo-variables with the data


$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);
}


// --------------------------------------------------------------------
//压缩传输的处理。
// Is compression requested?
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');
}
}
}


// --------------------------------------------------------------------
//设置http头信息
// Are there any server headers to send?
if (count($this->headers) > 0)
{
foreach ($this->headers as $header)
{
@header($header[0], $header[1]);
}
}


// --------------------------------------------------------------------


// Does the $CI object exist?
// If not we know we are dealing with a cache file so we'll
// simply echo out the data and exit.
//如果没有超级控制器,可以证明当前是在处理一个缓存的输出
if ( ! isset($CI))
{
//输出缓存内容。结束本函数。
echo $output;
log_message('debug', "Final output sent to browser");
log_message('debug', "Total execution time: ".$elapsed);
return TRUE;
}


// --------------------------------------------------------------------


// Do we need to generate profile data?
// If so, load the Profile class and run it.
//这里是一个评测器,如果有开启就调用,会生成一些报告到页面尾部用于辅助我们调试。我用CI的时候其实没有开启过
if ($this->enable_profiler == TRUE)
{
$CI->load->library('profiler');


if ( ! empty($this->_profiler_sections))
{
$CI->profiler->set_sections($this->_profiler_sections);
}


// If the output data contains closing </body> and </html> tags
// we will remove them and add them back after we insert the profile data
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();
}
}


// --------------------------------------------------------------------


// Does the controller contain a function named _output()?
// If so send the output there.  Otherwise, echo it.

  //如果我们有在当前的控制器里面定义了_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
*
* @access public
* @param string
* @return void
*/
//写入缓存。在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))
{
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;
}
按CI的格式写入缓存内容。
fclose($fp);
@chmod($cache_path, FILE_WRITE_MODE);


log_message('debug', "Cache file written: ".$cache_path);
}


// --------------------------------------------------------------------


/**
* Update/serve a cached file
*
* @access public
* @param object config class
* @param object uri class
* @return void
*/
//在CodeIgniter.php里面有调用此方法,此方法是负责缓存的输出,如果在CodeIgniter.php中调用此方法有输出,则
//本次请求的运行将直接结束,直接以缓存输出作为响应。
function _display_cache(&$CFG, &$URI)
{
取得保存缓存的路径
$cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');
//一条准确的路由都会对应一个缓存文件,缓存文件是对应路由字符串的md5密文。
// Build the file path.  The file name is an MD5 hash of the full URI
$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]是附加信息中和时间有关的信息。
// Strip out the embedded timestamp
if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
{
return FALSE;
}
//去掉TS--->后,利用剩下的数字判断缓存是否已经过期,如果过期了,就把它删除,同样视为获取缓存内容失败(过期),
  //返回FALSE
// Has the file expired? If so we'll delete it.
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()方法输出缓存。并返回
// Display the cache
$this->_display(str_replace($match['0'], '', $cache));
log_message('debug', "Cache file is current. Sending it to browser.");
return TRUE;
}




}
// END Output Class


/* End of file Output.php */
/* Location: ./system/core/Output.php */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值