ThinkPHP缓存机制

Posted on 2017-03-28 16:02  小阿杉  阅读(893)  评论(0编辑  收藏  举报
我们从S函数分析ThinkPHP框架缓存机制,像快速缓存、查询缓存、SQL解析缓存、静态缓存根本上都是在这种机制下运行,只是切入方式不同。

首先,看下S函数定义:
/**
* 缓存管理
* @param mixed $name 缓存名称,如果为数组表示进行缓存设置
* @param mixed $value 缓存值
* @param mixed $options 缓存参数
* @return mixed
*/
function S($name,$value='',$options=null) {
static $cache = '';
if(is_array($options) && empty($cache)){
// 缓存操作的同时初始化
$type = isset($options['type'])?$options['type']:'';
$cache = Think\Cache::getInstance($type,$options);
}elseif(is_array($name)) { // 缓存初始化
$type = isset($name['type'])?$name['type']:'';
$cache = Think\Cache::getInstance($type,$name);
return $cache;
}elseif(empty($cache)) { // 自动初始化
$cache = Think\Cache::getInstance();
}
if(''=== $value){ // 获取缓存
return $cache->get($name);
}elseif(is_null($value)) { // 删除缓存
return $cache->rm($name);
}else { // 缓存数据
if(is_array($options)) {
$expire = isset($options['expire'])?$options['expire']:NULL;
}else{
$expire = is_numeric($options)?$options:NULL;
}
return $cache->set($name, $value, $expire);
}
}
这个函数封装了缓存的创建、获取、删除操作,这部分功能很清新,关键在创建cache对象的时候函数调用了缓存基类:Think\Cache::getInstance 静态方法,通过这个方法框架支持:File、Db、Apc、Memcache、Shmop、Sqlite、Xcache、Apachenote、Eaccelerator不同类型的缓存方式,为了弄清楚支持这些缓存类型的代码结构,那么我们把这个方法代码看下:
/**
* 取得缓存类实例
* @static
* @access public
* @return mixed
*/
static function getInstance($type='',$options=array()) {
static $_instance=array();
$guid=$type.to_guid_string($options);
if(!isset($_instance[$guid])){
$obj=new Cache();
$_instance[$guid]=$obj->connect($type,$options);
}
//print_r($_instance);
return $_instance[$guid];
}

该方法调用了本类connect方法,在看下代码:
/**
* 连接缓存
* @access public
* @param string $type 缓存类型
* @param array $options 配置数组
* @return object
*/
public function connect($type='',$options=array()) {
if(empty($type)) $type = C('DATA_CACHE_TYPE');
$class = strpos($type,'\\')? $type : 'Think\\Cache\\Driver\\'.ucwords(strtolower($type)); 
if(class_exists($class))
$cache = new $class($options);
else
E(L('_CACHE_TYPE_INVALID_').':'.$type);
return $cache;
}
真正的区别缓存类型的代码在这里了,“Think\\Cache\\Driver\” 定义了框架支持的缓存类型,每种支持的缓存类型的文件在这里就是一个类文件。如果,没有定义缓存类型,框架获取了配置文件中“ C('DATA_CACHE_TYPE')”的默认值,我们再看下框架默认定义的缓存类型是什么:'DATA_CACHE_TYPE' => 'File', 很明显,框架默认使用的是File类型缓存机制。