class cache
{
private static $_instance = null; protected $_options = array(
'cache_dir' => "./",
'file_name_prefix' => 'cache',
'mode' => '1', //mode 1 为serialize model 2为保存为可执行文件
);
/**
* Get an instance of this class
*
* @return Ambiguous
*/
public static function getInstance()
{
if(self::$_instance === null)
{
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Get cache information
*
* @param string $id
* @return boolean|array
*/
public static function get($id)
{
$instance = self::getInstance();
//缓存文件不存在
if(!$instance->has($id))
{
return false;
}
$file = $instance->_file($id);
$data = $instance->_fileGetContents($file);
if($data['expire'] == 0 || time() < $data['expire'])
{
return $data['contents'];
}
return false;
}
/**
* Set up a cache
*
* @param string $id Cache id
* @param array $data cache content
* @param int $cacheLife Cache life Default is 0 unlimited life
*/
public static function set($id, $data, $cacheLife = 0)
{
$instance = self::getInstance();
$time = time();
$cache = array();
$cache['contents'] = $data;
$cache['expire'] = $cacheLife === 0 ? 0 : $time + $cacheLife;
$cache['mtime'] = $time;
$file = $instance->_file($id);
return $instance->_filePutContents($file, $cache);
}
/**
* Clear a cache
* *
* @param string cache id
* @return void
*/
public static function delete($id)
{
$instance = self::getInstance();
if(!$instance->has($id))
{
return false;
}
$file = $instance->_file($id);
//删除该缓存
return unlink($file);
}
/**
* Determine whether the cache exists
*
* @param string $id cache_id
* @return boolean true cache exists false cache does not exist
*/
public static function has($id)
{
$instance = self::getInstance();
$file = $instance->_file($id);
if(!is_file($file))
{
return false;
}
return true;
}
/**
* Get cache information path through cache id
* @param string $id
* @return string cache file path
*/
protected function _file($id)
{
$instance = self::getInstance();
$fileNmae = $instance->_idToFileName($id);
return $instance->_options['cache_dir'] . $fileNmae;
}
/**
* Get cache information storage file name through id
*
* @param $id
* @return string cache file name
*/
protected function _idToFileName($id)
{
$instance = self::getInstance();
$prefix = $instance->_options['file_name_prefix'];
return $prefix . '---' . $id;
}
/**
* 通过filename得到缓存id
* * @param $id
* @return string 缓存id
*/
protected function _fileNameToId($fileName)
{
$instance = self::getInstance();
$prefix = $instance->_options['file_name_prefix'];
return preg_replace('/^' . $prefix . '---(.*)$/', '$1', $fileName);
}
/**
* Write data to file
*
* @param string $file file name
* @param array $contents data content
* @return bool
*/
protected function _filePutContents($file, $contents)
{
if($this->_options['mode'] == 1)
{
$contents = serialize($contents);
}
else
{
$time = time();
$contents = "
" // mktime: ". $time. "n".
" return ".
var_export($contents, true).
"n?>";
}
$result = false;
$f = @fopen($file, 'w');
if ($f) {
@flock($f, LOCK_EX);
fseek($f, 0);
ftruncate($f, 0);
$tmp = @fwrite($f, $contents);
if (!($tmp === false)) {
$result = true;
}
@fclose($f);
}
@chmod($file,0777);
return $result;
}
/**
* Get data from file
*
* @param sring $file
* @return boolean|array
*/
protected function _fileGetContents($file)
{
if(!is_file($file))
{
return false;
}
if($this->_options['mode'] == 1)
{
$f = @fopen($file, 'r');
@$data = fread($f,filesize($file));
@fclose($f);
return unserialize($data);
}
else
{
return include $file;
}
}
/**
* Constructor
*/
protected function __construct()
{
}
/**
* Set cache path
*
* @param string $path
* @return self
*/
public static function setCacheDir($path)
{
$instance = self::getInstance();
if (!is_dir($path)) {
exit('file_cache: ' . $path.' 不是一个有效路径 ');
}
if (!is_writable($path)) {
exit('file_cache: 路径 "'.$path.'" 不可写');
}
$path = rtrim($path,'/') . '/';
$instance->_options['cache_dir'] = $path;
return $instance;
}
/**
* Set cache file prefix
*
* @param srting $prefix
* @return self
*/ public static function setCachePrefix($prefix)
{
$instance = self::getInstance();
$instance->_options['file_name_prefix'] = $prefix;
return $instance;
}
/**
* Set cache storage type
*
* @param int $mode
* @return self
*/
public static function setCacheMode($mode = 1)
{
$instance = self::getInstance();
if($mode == 1)
{
$instance->_options['mode'] = 1;
}
else
{
$instance->_options['mode'] = 2;
}
return $instance;
}
/**
* Delete all caches
* @return boolean
*/
public static function flush()
{
$instance = self::getInstance();
$glob = @glob($instance->_options['cache_dir'] . $instance->_options['file_name_prefix'] . '--*');
if(empty($glob))
{
return false;
}
foreach ($glob as $v)
{
$fileName = basename($v);
$id = $instance->_fileNameToId($fileName);
$instance->delete($id);
}
return true;
}
}
/* 初始化设置cache的配置信息什么的 */
cache::setCachePrefix('core'); //设置缓存文件前缀
cache::setCacheDir('./cache'); //设置存放缓存文件夹路径
//模式1 缓存存储方式
//a:3:{s:8:"contents";a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:34;i:4;i:5;i:5;i:6;i:6;i:6;}s:6:"expire";i:0;s:5:"mtime";i:1318218422;}
//模式2 缓存存储方式
/*
// mktime: 1318224645
return array (
'contents' =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 34,
4 => 5,
5 => 6,
6 => 6,
),
'expire' => 0,
'mtime' => 1318224645,
)
?>
*
*
*/
cache::setCacheMode('2');
if(!$row = cache::get('zj2'))
{
$array = array(1,2,3,34,5,6,6);
$row = cache::set('zj2',$array);
}
// cache::flush(); 清空所有缓存
print_r($row);
件缓存 class
/**
* File cache class
* @author xiaojiong & 290747680@qq.com
* @date 2011-08-17
*/
class cache
{
const FILE_LIFE_KEY = 'FILE_LIFE_KEY';
const CLEAR_ALL_KEY = 'CLEAR_ALL';
static $_instance = null;
protected $_options = array(
'cache_dir' => './cache',
'file_locking' => true,
'file_name_prefix' => 'cache',
'cache_file_umask' => 0777,
'file_life' => 100000
);
static function &getInstance($options = array())
{
if(self::$_instance === null)
{
self::$_instance = new self($options);
}
return self::$_instance;
}
/**
*Set parameters
* @param array $options cache parameters
* @return void
*/
static function &setOptions($options = array())
{
return self::getInstance($options);
}
/**
* Constructor
* @param array $options cache parameters
* @return void
*/
private function __construct($options = array())
{
if ($this->_options['cache_dir'] !== null) {
$dir = rtrim($this->_options['cache_dir'],'/') . '/';
$this->_options['cache_dir'] = $dir;
if (!is_dir($this->_options['cache_dir'])) {
mkdir($this->_options['cache_dir'],0777,TRUE);
}
if (!is_writable($this->_options['cache_dir'])) {
exit('file_cache: 路径 "'. $this->_options['cache_dir'] .'" 不可写');
}
} else {
exit('file_cache: "options" cache_dir 不能为空 ');
}
}
/**
* Set cache path
* @param string $value
* @return void
*/
static function setCacheDir($value)
{
$self = & self::getInstance();
if (!is_dir($value)) {
exit('file_cache: ' . $value.' 不是一个有效路径 ');
}
if (!is_writable($value)) {
exit('file_cache: 路径 "'.$value.'" 不可写');
}
$value = rtrim($this->_options['cache_dir'],'/') . '/';
$self->_options['cache_dir'] = $value;
}
/**
* * Save cache data
* @param array $data The data put into the cache
* @param string $id Cache id (also known as cache identification code)
* @param cache_life Cache time
* @return boolean True if no problem
*/
static function save($data, $id = null, $cache_life = null)
{
$self = & self::getInstance();
if (!$id) {
if ($self->_id) {
$id = $self->_id;
} else {
exit('file_cache:save() id 不能为空!');
}
}
$time = time();
if($cache_life) {
$data[self::FILE_LIFE_KEY] = $time + $cache_life;
}
elseif
($cache_life != 0){
$data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life'];
}
$file = $self->_file($id);
$data = "
" // mktime: ". $time. "n".
" return ".
var_export($data, true).
"n?>"
;
$res = $self->_filePutContents($file, $data);
return $res;
}
/**
* Get cache information
*
* @param string $id cache id
* @return string|array cache data
*/
static function load($id)
{
$self = & self::getInstance();
$time = time(); //Check whether the cache exists
If (!$self->test($id)) {
// The cache is not hit !
return false;
}
//Clear all identification files
$clearFile = $self->_file(self::CLEAR_ALL_KEY);
$file = $self->_file($id);
//Determine whether the cache has been cleared entirely
If(is_file($clearFile) && filemtime($clearFile) > filemtime($file))
{
Return false;
}
$data = $self->_fileGetContents($file);
If(empty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) {
unset($data[self::FILE_LIFE_KEY]);
return $data;
}
Return false;
}
/**
* Write cache file
*
* @param string $file Cache path
* @param string $string cache information
* @return boolean true success
*/
Protected function _filePutContents($file, $string)
{
$self = & self::getInstance();
$result = false;
$f = @fopen($file, 'ab+');
if ($f) {
If ($self->_options['file_locking']) @flock($f, LOCK_EX);
fseek($f, 0);
ftruncate($f, 0);
$tmp = @fwrite($f, $string);
If (!($tmp === false)) {
$result = true;
}
@fclose($f);
}
@chmod($file, $self->_options['cache_file_umask']);
return $result;
}
/**
* * Formatted cache file path
*
* @param string $id cache id
* @return string cache file name (including path)
*/
Protected function _file($id)
{
$self = & self::getInstance();
$fileName = $self->_idToFileName($id);
return $self->_options['cache_dir'] . $fileName;
}
/**
* * Formatted cache file name
*
* @param string $id cache id
* @return string cache file name
*/
Protected function _idToFileName($id)
{
$self = & self::getInstance();
$self->_id = $id;
$prefix = $self->_options['file_name_prefix'];
$result = $prefix . '---' . $id;
return $result;
}
/** * 判断缓存是否存在
*
* @param string $id Cache id
* @return boolean True 缓存存在 False 缓存不存在
*/
static function test($id)
{
$self = & self::getInstance();
$file = $self->_file($id);
if (!is_file($file)) {
return false;
}
return true;
}
/**
* Get cache information
*
* @param string $file cache path
* @return string cache content
*/
protected function _fileGetContents($file)
{
if (!is_file($file)) {
return false;
}
return include $file;
}
/**
* Clear all cache
* *
* @return void
*/
static function clear()
{
$self = & self::getInstance();
$self->save('CLEAR_ALL',self::CLEAR_ALL_KEY);
}
/**
* Clear a cache
* *
* @param string cache id
* @return void
*/
static function del($id)
{
$self = & self::getInstance();
if(!$self->test($id)){
// 该缓存不存在
return false;
}
$file = $self->_file($id);
return unlink($file);
}
}
存入数据
$config = array(
'name' => 'xiaojiong',
'qq' => '290747680',
'age' => '20',
);
//第一个参数 缓存data
//第二个参数 缓存id
//第三个参数 cache_life 0 永不过期(cache::clear()清空所有除外) 默认cache_life 为option_cache_life
cache::save($config,'config',0);
载入数据
//只有一个参数 cache_id
$config = cache::load('config');
清空缓存
//清空指定缓存
cache::del('config');
//清空所有缓存
cache::clear();
cache信息配置
//在执行所有cache_func前调用
$_options = array(
'cache_dir' => './cache', //缓存文件目录
'file_name_prefix' => 'cache',//缓存文件前缀
'file_life' => 100000, //缓存文件生命
);
cache::setOptions($options);
//再执行 就会按着新配置信息执行,否则是默认信息
cache::save($arr,'arr');
//就是这个方法 貌似不合理 望大家指点
|