输出类 大致情况总结
设置http头信息、设置文件类型加入到header、设置缓存
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CI_Output {
protected $final_output;
protected $cache_expiration = 0;
protected $headers = array();
protected $mime_types = array();
protected $enable_profiler = FALSE;
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;
function __construct()
{
$this->_zlib_oc = @ini_get('zlib.output_compression');
// 加载confg/mimes文件 用于设置输出的头部文件类型那个描述
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;//将config/mimes文件中的mimes数组复制给类成员属性
log_message('debug', "Output Class Initialized");
}
function get_output()
{
return $this->final_output;
}
function set_output($output)
{
$this->final_output = $output;
return $this;
}
function append_output($output)
{
if ($this->final_output == '')
{
$this->final_output = $output;
}
else
{
$this->final_output .= $output;
}
return $this;
}
// 设置响应头信息
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.
/*
如果开启zlib压缩 http头相应中的content-length是不会被改变,这导致浏览器等待接收数据
在设置header的时候开启zlib压缩 如果请求中有content-length 这不会去设置头信息
*/
if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0)
{
return;
}
$this->headers[] = array($header, $replace);
return $this;
}
// 设置文件类型
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;
}
// 设置响应头部状态信息
function set_status_header($code = 200, $text = '')
{
set_status_header($code, $text);
return $this;
}
function enable_profiler($val = TRUE)
{
$this->enable_profiler = (is_bool($val)) ? $val : TRUE;
return $this;
}
function set_profiler_sections($sections)
{
foreach ($sections as $section => $enable)
{
$this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE;
}
return $this;
}
// 设置文件缓存时间 控制器中调用这个方法就会生成缓存文件 读取的时候也是直接读取缓存文件
function cache($time)
{
$this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time;
return $this;
}
// 展示内容
function _display($output = '')
{
global $BM, $CFG;
if (class_exists('CI_Controller'))
{
$CI =& get_instance();//加载super class $CI
}
if ($output == '')
{
$output =& $this->final_output;
}
// 调用 _write_cache 生成缓存文件
if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
{
$this->_write_cache($output);
}
$elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
if ($this->parse_exec_vars === TRUE)
{//性能分析
$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)
{
// zlib模块加载 且 浏览器支持gzip压缩格式
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;
}
// Do we need to generate profile data?
// If so, load the Profile class and run it.
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
{
echo $output; // Send it to the browser!
}
log_message('debug', "Final output sent to browser");
log_message('debug', "Total execution time: ".$elapsed);
}
// 生成缓存文件
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;
}
fclose($fp);
@chmod($cache_path, FILE_WRITE_MODE);
log_message('debug', "Cache file written: ".$cache_path);
}
// 显示缓存文件 CodeIgniter 中调用
function _display_cache(&$CFG, &$URI)
{
// 缓存文件存放的路径
$cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');
// 文件uri路径 md5 一下就是缓存文件的文件名
$uri = $CFG->item('base_url').
$CFG->item('index_page').
$URI->uri_string;
// filepath 是缓存文件完整路径
$filepath = $cache_path.md5($uri);
if ( ! @file_exists($filepath))
{
return FALSE;//不存在
}
if ( ! $fp = @fopen($filepath, FOPEN_READ))
{
return FALSE;//read 打开失败
}
flock($fp, LOCK_SH);//加读文件锁
$cache = '';
if (filesize($filepath) > 0)
{
// 文件内容不空读取内容到 cache 缓存
$cache = fread($fp, filesize($filepath));
}
flock($fp, LOCK_UN);//解锁
fclose($fp);
//缓存文件开始格式不对
if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
{
return FALSE;
}
//文件过期
if (time() >= trim(str_replace('TS--->', '', $match['1'])))
{
if (is_really_writable($cache_path))
{
// 文件可写 删除文件 返回FALSE
@unlink($filepath);
log_message('debug', "Cache file has expired. File deleted");
return FALSE;
}
}
//显示缓存文件
$this->_display(str_replace($match['0'], '', $cache));
log_message('debug', "Cache file is current. Sending it to browser.");
return TRUE;
}
}
Code Tips:
创建读取缓存文件 以及头信息中zlib的处理