codeigniter源代码分析之系统全局函数 Common.php

Common.php 文件里面共有这些函数 以及功能说明

is_php				比较php版本

is_really_writable		文件夹是否可写

load_class			加载并实例化类

is_loaded			记录已经加载的类

get_config			获取config 参数可以替换掉对应项的值

config_item			获取相应config项的值

show_error			错误处理

show_404			404处理

log_message			写入日志

set_status_header		http响应头信息

_exception_handler		用户级别脚本错误处理函数

remove_invisible_characters	去除字符串或url中不可见(无效无用)字符

具体 代码注释如下

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('is_php'))
{
	/*
		当前版本 < 指定版本		false
		当前版本 > 指定版本		true
	*/
	function is_php($version = '5.0.0')
	{
		// static 做缓存
		static $_is_php;
		$version = (string)$version;

		if ( ! isset($_is_php[$version]))
		{
			$_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
		}

		return $_is_php[$version];
	}
}
if ( ! function_exists('is_really_writable'))
{
	/*
		检测文件是否可写
	*/
	function is_really_writable($file)
	{
		if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
		{
			// linux 系统 可直接调用 is_writable()
			return is_writable($file);
		}
		// windows 系统通过写入文件检测是否可写
		if (is_dir($file))
		{
			$file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100));//创建一个随机文件名的文件到指定目录
			if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
			{
				return FALSE;//写入失败 不可写
			}
			fclose($fp);
			//修改文件权限并删除文件
			@chmod($file, DIR_WRITE_MODE);
			@unlink($file);
			return TRUE;
		}
		//不是文件 或 fopen无法打开
		elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
		{
			return FALSE;
		}

		fclose($fp);
		return TRUE;
	}
}
if ( ! function_exists('load_class'))
{
	/*
		重要函数 加载并实例化类文件
	*/
	function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
	{
		static $_classes = array();//静态化 存放的是类的引用
		if (isset($_classes[$class]))
		{
			return $_classes[$class];//请求的class已经加载过 直接返回
		}
		$name = FALSE;
		foreach (array(APPPATH, BASEPATH) as $path)//遍历目录 优先遍历APPPATH 检测是否有用户覆盖的class
		{
			if (file_exists($path.$directory.'/'.$class.'.php'))//通过文件名找到
			{
				$name = $prefix.$class;//加上前缀形成类名
				if (class_exists($name) === FALSE)
				{//类未被加载过 加载文件
					require($path.$directory.'/'.$class.'.php');
				}
				break;
			}
		}
		//若 APPPATH中存在扩展类 加载之
		if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
		{
			$name = config_item('subclass_prefix').$class;
			if (class_exists($name) === FALSE)
			{
				require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php');
			}
		}
		if ($name === FALSE)
		{
			exit('Unable to locate the specified class: '.$class.'.php');//未找到请求加载的class
		}
		is_loaded($class);//记录加载的类名
		$_classes[$class] = new $name(); // 实例化class 将实例化类存储到数组 $_classes[$class]
		return $_classes[$class];
	}
}
if ( ! function_exists('is_loaded'))
{
	//记录加载的类名 在ci_controller 里面根据这个将所有的核心class绑定到 ci_controller
	function &is_loaded($class = '')
	{
		static $_is_loaded = array();
		if ($class != '')
		{
			$_is_loaded[strtolower($class)] = $class;// $_is_loaded[classname]=ClassName;
		}
		return $_is_loaded;
	}
}
if ( ! function_exists('get_config'))
{
	function &get_config($replace = array())
	{
		static $_config;
		if (isset($_config))
		{
			return $_config[0];//存在config直接返回
		}
		if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php'))
		{
			$file_path = APPPATH.'config/config.php';
		}
		if ( ! file_exists($file_path))
		{
			exit('The configuration file does not exist.');//配置文件不存在
		}
		require($file_path);//加载配置文件 config


		if ( ! isset($config) OR ! is_array($config))
		{
			exit('Your config file does not appear to be formatted correctly.');//配置项不符合规范
		}
		if (count($replace) > 0)
		{
			foreach ($replace as $key => $val)
			{
				if (isset($config[$key]))
				{
					$config[$key] = $val;//replace替换config中的对应配置项的值
				}
			}
		}
		return $_config[0] =& $config;
	}
}
if ( ! function_exists('config_item'))
{
	function config_item($item)
	{
		static $_config_item = array();
		if ( ! isset($_config_item[$item]))
		{//缓存配置项中没有请求的配置项的值
			$config =& get_config();
			if ( ! isset($config[$item]))
			{
				return FALSE;
			}
			$_config_item[$item] = $config[$item];//缓存
		}
		return $_config_item[$item];
	}
}
if ( ! function_exists('show_error'))
{
	function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')
	{
		$_error =& load_class('Exceptions', 'core');
		echo $_error->show_error($heading, $message, 'error_general', $status_code);// 调用Exceptions的show_error方法
		exit;
	}
}
if ( ! function_exists('show_404'))
{
	function show_404($page = '', $log_error = TRUE)
	{
		$_error =& load_class('Exceptions', 'core');
		$_error->show_404($page, $log_error); // 调用Exceptions的show_404方法
		exit;
	}
}
if ( ! function_exists('log_message'))
{
	function log_message($level = 'error', $message, $php_error = FALSE)
	{
		static $_log;

		if (config_item('log_threshold') == 0)
		{
			return;
		}

		$_log =& load_class('Log');
		$_log->write_log($level, $message, $php_error);
	}
}
if ( ! function_exists('set_status_header'))
{
	// http相应头
	function set_status_header($code = 200, $text = '')
	{
		$stati = array(
			200	=> 'OK',
			201	=> 'Created',
			202	=> 'Accepted',
			203	=> 'Non-Authoritative Information',
			204	=> 'No Content',
			205	=> 'Reset Content',
			206	=> 'Partial Content',

			300	=> 'Multiple Choices',
			301	=> 'Moved Permanently',
			302	=> 'Found',
			304	=> 'Not Modified',
			305	=> 'Use Proxy',
			307	=> 'Temporary Redirect',

			400	=> 'Bad Request',
			401	=> 'Unauthorized',
			403	=> 'Forbidden',
			404	=> 'Not Found',
			405	=> 'Method Not Allowed',
			406	=> 'Not Acceptable',
			407	=> 'Proxy Authentication Required',
			408	=> 'Request Timeout',
			409	=> 'Conflict',
			410	=> 'Gone',
			411	=> 'Length Required',
			412	=> 'Precondition Failed',
			413	=> 'Request Entity Too Large',
			414	=> 'Request-URI Too Long',
			415	=> 'Unsupported Media Type',
			416	=> 'Requested Range Not Satisfiable',
			417	=> 'Expectation Failed',

			500	=> 'Internal Server Error',
			501	=> 'Not Implemented',
			502	=> 'Bad Gateway',
			503	=> 'Service Unavailable',
			504	=> 'Gateway Timeout',
			505	=> 'HTTP Version Not Supported'
		);

		if ($code == '' OR ! is_numeric($code))
		{
			show_error('Status codes must be numeric', 500);
		}

		if (isset($stati[$code]) AND $text == '')
		{
			$text = $stati[$code];
		}

		if ($text == '')
		{//code is wrong
			show_error('No status text available.  Please check your status code number or supply your own message text.', 500);
		}

		$server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE;

		if (substr(php_sapi_name(), 0, 3) == 'cgi')
		{
			header("Status: {$code} {$text}", TRUE);//cgi模式
		}
		elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0')
		{
			header($server_protocol." {$code} {$text}", TRUE, $code);//http模式
		}
		else
		{//默认http模式
			header("HTTP/1.1 {$code} {$text}", TRUE, $code);
		}
	}
}
if ( ! function_exists('_exception_handler'))
{
	// error_handler 接管php中用户级别的错误处理
	function _exception_handler($severity, $message, $filepath, $line)
	{
		if ($severity == E_STRICT)
		{
			return;
		}
		$_error =& load_class('Exceptions', 'core');
		if (($severity & error_reporting()) == $severity)
		{
			$_error->show_php_error($severity, $message, $filepath, $line);
		}
		if (config_item('log_threshold') == 0)
		{
			return;
		}
		$_error->log_exception($severity, $message, $filepath, $line);
	}
}
if ( ! function_exists('remove_invisible_characters'))
{
	// 替换掉 无法直接显示的URL编码和ASCII码
	function remove_invisible_characters($str, $url_encoded = TRUE)
	{
		$non_displayables = array();		
		if ($url_encoded)
		{
			$non_displayables[] = '/%0[0-8bcef]/';	// url encoded 00-08, 11, 12, 14, 15
			$non_displayables[] = '/%1[0-9a-f]/';	// url encoded 16-31
		}
		$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';	// 00-08, 11, 12, 14-31, 127
		do
		{
			$str = preg_replace($non_displayables, '', $str, -1, $count);//$count 将会被 整个操作的替换次数引用赋值
		}
		while ($count);

		return $str;
	}
}
if ( ! function_exists('html_escape'))
{
	// 将HTML预定义字符(& ' " < >) 替换成实体
	function html_escape($var)
	{
		if (is_array($var))
		{
			return array_map('html_escape', $var);
		}
		else
		{
			return htmlspecialchars($var, ENT_QUOTES, config_item('charset'));
		}
	}
}

Code Tips:

1、在 load_class中 65 - 69行 用静态变量防止类被重复实例化

static $_classes = array();//静态化 存放的是类的引用
if (isset($_classes[$class]))
{
	return $_classes[$class];//请求的class已经加载过 直接返回
}


2、函数 config_item 里面的缓存是通过在获取一个个config item的过程中缓存下来的

function config_item($item)
{
	static $_config_item = array();
	if ( ! isset($_config_item[$item]))
	{
		$config =& get_config();
<span style="white-space:pre">	</span>	if ( ! isset($config[$item]))
		{
			return FALSE;
		}
		$_config_item[$item] = $config[$item];//缓存 只缓存一项
	}
	return $_config_item[$item];
}

个人思路:每次调用去get_config 获取所有配置 然后在里面寻找查找项 省去缓存(不过速度会比ci写法慢,ci中很多函数的写法很科学)


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值