ThinkPHP5.0源码学习之缓存Cache(一)


一、文件 1、缓存配置文件:thinkphp\convention.php 2、缓存文件:thinkphp\library\think\Cache.php 3、驱动目录:thinkphp\library\think\cache\driver,包含8个文件:File.php、Lite.php、Memcache.php、Memcached.php、Redis.php、Sqlite.php、Wincache.php、Xcache.php,通过文件名可知其对应的缓存类型。   二、缓存配置 在全局配置文件convention.php中可以看到,type就是驱动方式,默认使用的是File文件驱动,实例化的是\think\cache\driver\File.class。可以通过修改type来使用不同的驱动。   三、Cache.php文件分析 $instance-缓存的实例 $readTimes-缓存读取次数 $writeTimes-缓存写入次数 $handler-操作句柄 1、缓存初始化 首先,句柄handler为空时才会去初始化对象,否则直接返回句柄。 其次,通过传入不同的配置信息,连接对应的缓存驱动。   2、连接缓存驱动 第50行: $name = md5(serialize($options));   将配置参数进行序列化(serialize)后,再进行md5操作,得到的结果作为缓存对象索引; 第53行: if (true === $name || !isset(self::$instance[$name])) {}   检查$instance中是否存在对应索引的缓存对象 第54-56行: $class = false === strpos($type, '\\') ? '\\think\\cache\\driver\\' . ucwords($type) : $type;   class的名字由type决定,  如果type没有包含反斜线, 则class = \think\cache\driver\.ucwords($type), 而框架是把think作为核心目录的别名,所以其真实路径为\thinkphp\libray\\think\driver\.ucwords($type), 再根据自动加载,去该文件夹下加载对应的对象; 第65行: self::$instance[$name] = new $class($options);   通过这句代码可以知道init()方法中句柄的内容,是这个方法中创建的缓存对象,并通过第67行的return返回。 connect的目的是:return new \$class(\$option),如果是true,就不存,如果是flase,就存到\$instance[\$name]里面。   四、缓存驱动接口
方法名 用途 参数
public static function has($name){} 判断缓存是否存在 $name 缓存变量名
public static function get(\$name, $default = false){} 读取缓存 $name 缓存变量名 $default 默认值
public static function set(\$name, \$value, \$expire = null){} 写入缓存 $name 缓存变量名 $value 存储数据 $expire 有效时间 0为永久
public static function inc(\$name, $step = 1){} 自增缓存 $name 缓存变量名 $step 步长
public static function dec(\$name, $step = 1){} 自减缓存 $name 缓存变量名 $step 步长
public static function rm($name){} 删除缓存 $name 缓存标识
public static function clear($tag = null){} 清除缓存 $tag 标签名
public static function pull($name){} 读取缓存并删除 $name 缓存变量名
public static function remember(\$name, \$value, \$expire = null){} 如果不存在则写入缓存 $name 缓存变量名 $value 存储数据 $expire 有效时间 0为永久
public static function tag(\$name, \$keys = null, \$overlay = false) 缓存标签 $name 标签名 $keys 缓存标识 $overlay 是否覆盖