Home > Backend Development > PHP Tutorial > php 抽象缓存种

php 抽象缓存种

WBOY
Release: 2016-06-13 13:02:29
Original
972 people have browsed it

php 抽象缓存类
require_once dirname(__FILE__)."/../Model/Iface/Icache.php";
abstract class AllCache implements Icache
{
static  $cache_dir;
const   CACHETIME=60;//缓存的时间是 60 秒
static  $_data;
static  $_interce;
//构造函数
public function __construct()
{
        $cache_dirname = dirname(__FILE__)."/../Cache";
if(!@is_dir($cache_dirname))
{
if(!@mkdir($cache_dirname,0777))
{
self::msgbox('缓存文件不存在而且不能创建,需要手动创建.');
return false;
}
}
self::$cache_dir = $cache_dirname;
}
/**
* 静态调用
* self 指类本身
*/
public static function getInstance()
{
if(! (self::$_interce instanceof self)){
self::$_interce = new self();
}
return self::$_interce;
}
//输出异常
private function msgbox($errorstring)
{
echo "发生错误:

".$errorstring."
Copy after login
";
}
    //设定缓存文件
private function cache_page($pageurl,$pagedata)
{
if(!$fso=fopen($pageurl,'w')){
self::msgboxs('无法打开缓存文件.');//trigger_error
return false;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型锁定
self::msgboxs('无法锁定缓存文件.');//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//写入字节流,serialize写入其他格式
self::msgboxs('无法写入缓存文件.');//trigger_error
return false;
}
flock($fso,LOCK_UN);//释放锁定
fclose($fso);
return true;
}
    //读取文件状态
private function isOpenCache($cacheFile)
{
if(!file_exists($cacheFile)){
self::msgbox('无法读取缓存文件.');exit;
}
/*echo '读取缓存文件:'.$cacheFile;
return unserialize(file_get_contents($cacheFile));
$fso = fopen($cacheFile, 'r');
$data = fread($fso, filesize($cacheFile));
fclose($fso);
return $data;*/
}

/**
* 格式化数据
*/
private function setFileContent($data)
{
$html = " $html .="\$data= ".var_export($data, true).";\n";
$html .="?>";
return $html;
}

/**
*  设置缓存数据
* @param $cacheFile 缓存文件名
× @param $_data     缓存数据源
*/
public function readData($cacheFile='default_cache.txt',$_data)
{
$_data = self::SetFileContent($_data);
$cacheFile = self::$cache_dir."/".$cacheFile;
if(file_exists($cacheFile))
{
self::isOpenCache($cacheFile);
if(filemtime($cacheFile) {
self::cache_page($cacheFile,$_data);
}
}else{
self::cache_page($cacheFile,$_data);
}
require_once($cacheFile);
self::$_data = $data;
}

/**
* 获取数据
*/
public function GetData()
{
return self::$_data;
}
}
/*
AllCache::readData("cache_news.php",array(0,1,2,3,5,6));
print_r(AllCache::GetData());
*/
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template