Skip to content

Instantly share code, notes, and snippets.

@horsley
Last active December 27, 2015 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save horsley/7280740 to your computer and use it in GitHub Desktop.
Save horsley/7280740 to your computer and use it in GitHub Desktop.
一种简单的文件缓存,git风格的存储结构,简答的序列化
<?php
/**
* 简单文件缓存
* @author: horsley
* @version: 2013-11-04
*/
class Cache {
//内存缓存,跟磁盘缓存保持一致格式
//消耗内存,但可减少一次请求内的磁盘io次数,并加速读取(命中时)
private static $data_cache = array();
/**
* 缓存读取
* @param $partition
* @param $key
* @param bool $serialize
* @return bool|mixed|null|string
*/
public static function get($partition, $key, $serialize = true) {
//运行时内存缓存
if (isset(self::$data_cache[$partition])
&& isset(self::$data_cache[$partition][$key])
) {
$data = self::$data_cache[$partition][$key];
if ($serialize) {
$data = unserialize($data);
}
return $data;
}
//磁盘缓存
$file = self::get_raw_filename($partition, $key);
if (!file_exists($file)) {
return null;
}
if ($data = file_get_contents($file)) {
return $serialize ? unserialize($data) : $data;
} else {
return false;
}
}
/**
* 缓存写入
* @param string $partition 文件存放分区,方便有针对性清除缓存,可以加/生成子目录结构
* @param $key 缓存键名
* @param string $value 设置为null删除缓存
* @param bool $serialize 是否需要序列化再存储,读写要对应设置
* @return mixed|null 缓存不存在返回null
*/
public static function set($partition, $key, $value = '', $serialize = true) {
//运行时内存缓存
if (!isset(self::$data_cache[$partition])) {
self::$data_cache[$partition] = array();
}
self::$data_cache[$partition][$key] = $serialize ? serialize($value) : $value;
//磁盘缓存
$file = self::get_raw_filename($partition, $key);
if ($value === null) { //删除
if(file_exists($file)) {
return unlink($file);
}
return false;
} else { //写入
$dir = dirname($file);
if (!file_exists($dir)) {
mkdir($dir, 0755, true);
}
if ($serialize) {
$value = serialize($value);
}
return file_put_contents($file, $value) !== false;
}
}
/**
* 获取缓存实际存放的文件名
* @param $partition
* @param $key
* @return string
*/
public static function get_raw_filename($partition, $key) {
$hash = sha1($key);
$dir = APP_CACHE_DIR .$partition.'/'. substr($hash, 0, 2);
$file = $dir . '/'. substr($hash, 2);
return $file;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment