清如许工作室PHP框架缓存源码分析
PHP 使用文件缓存方式,可以把频繁查询数据库的内容存放起来,减少对数据库的读写,从而提高性能,而PHP序列化的方法有很多,不过效率不是很高,清如许工作室自写了一套,支持数组,普通字符串,多维数组的序列化方法,以下是源码。<?php
if(!defined('QRX')) exit('Request Error!');
/**
* 缓存类
*/
class cache {
//缓存路径
private $cache_path;
/**
* 构造函数
* @param 缓存保存路径 $cache_path
*/
function __construct($cache_path)
{
$this->cache_path = $cache_path;
}
/**
* 写入缓存
* @param 键 $key
* @param 值 $val
*/
function set($key,$val)
{
$serialize = '<?php if(!defined(\'ROOTPATH\')) exit(\'Request Error!\'); return '.$this->array_serialize($val).' ?>';
file_put_contents(ROOTPATH.$this->cache_path.$key.'.php',$serialize);
}
/**
* 读取缓存
* @param 键 $key
* @return 值
*/
function get($key)
{
$cache_file = ROOTPATH.$this->cache_path.$key.'.php';
if(file_exists($cache_file))
{
return include $cache_file;
}
return '';
}
/**
* 清除缓存
*/
function clean()
{
foreach (glob($this->cache_path.'*.php') as $cache_file)
{
@unlink($cache_file);
}
}
/**
* 数组序列化 (支持多维数组)
* @param 需要序列化的数组 $array
* @param 不用填写 $content
* @return 序列化后内容
*/
private function array_serialize($array,$content='')
{
if(is_array($array))
{
$content .='array(';
foreach ($array as $k=>$v)
{
if(is_array($v))
{
$content .= $this->array_serialize($v);
}
else
{
$content .= "'$k'=>'$v',";
}
}
$content .='),';
}
else
{
$content .= $array;
}
return substr($content,0,-1);
}
}
?>
- 上一篇:apache2.2 重写规则问题
- 下一篇:php一般开发网站注意事项