以文件形式缓存php变量的方法


Posted in PHP onJune 26, 2015

本文实例讲述了以文件形式缓存php变量的方法。分享给大家供大家参考。具体实现方法如下:

<?php
/*
$cache_set = array(
//缓存路径 , 最后要加"/"
'cacheRoot'=>'./cache/',
//缓存时间
'cacheTime'=>20,
//cache type
'cacheType'=>1,
//扩展名
'cacheExe'=>'.php'
);
$cache = new Cache($cache_set);
$a=array('1','2');
$a="aaa";
$b='';
if($cache->cache_is("d")){
 $c=$cache->cache_read("d");
 echo "c";
 print_r($c);
}else {
$b=$cache->cache_data('d',$a);
}
print_r($b);
//$cache->clear("a");
//echo $cache->cache_read("./cache/d.php");
//echo $d;
*/
/**
 * 数据缓存类 v1.0
 * @author shooke
 * 2009-11-13 16:02:26
 * 用于缓存数据,如变量,但不能缓存页面
 */
class Cache{
 //配置
 public $config = array(
 //缓存路径
 'cacheRoot'=>'./cache/',
 //缓存时间
 'cacheTime'=>1,
 //cache 类型 1串化数据 2变量
 'cacheType'=>2,
 //扩展名
 'cacheExe'=>'.php'
 //转换中间变量
 );
 public $return_name=array();
 function __construct($cache_set = array())
 {
  if(!empty($cache_set)) $this->config=array_merge($this->config,$cache_set);
  $this->config['ClassName'] = __CLASS__;
 }
 public function clear($filename=''){
  if (file_exists($this->cache_file($filename))) {
   @unlink($this->cache_file($filename));
  }elseif (empty($filename)){
   $this->clear_dir($this->config['cacheRoot']);
  }else{
   $this->clear_dir($this->config['cacheRoot'].$filename);
   echo $this->config['cacheRoot'].$filename;
  }
 }
 //循环删除路径
 private function clear_dir($dir,$to = false)
 {
  if ($list = glob($dir.'/*'))
  {
   foreach ($list as $file)
   {
    is_dir($file) ? $this->clear_dir($file) : unlink($file);
   }
  }
  if ($to === false) rmdir($dir);
 }
 //写入缓存
 private function cache_write($filename, $writetext, $openmod='w'){
  if (!file_exists($filename)) {
   @$this->makeDir( dirname($filename ));
  }
  if(@$fp = fopen($filename, $openmod)) {
   flock($fp, 2);
   fwrite($fp, $writetext);
   fclose($fp);
   return true;
  } else {
   echo "File: $filename write error.";
   return false;
  }
 }
 //缓存有效期 有效返回 true
 public function cache_is($fileName){
  $fileName=$this->cache_file($fileName);
  if( file_exists( $fileName ) ) {
   //如果缓存时间为负数则永不过期
   if ($this->config['cacheTime'] < 0) {
    return true;
   }
   //如果缓存时间为0则一直过期
   if ($this->config['cacheTime'] == 0) {
    return false;
   }
   //获取缓存文件的建立时间
   $ctime = intval(filemtime( $fileName ));
   //比较是否大于缓存时间,是则过期 否则不过期
   if (time() - $ctime > $this->config['cacheTime']) {
    return false;
   }else {
    return true;
   }
   //文件不存在视为过期失效
  }else {
   return false;
  }
 }
 public function cache_data($name,$data){
  $varname=$name;
  $name = $this->cache_file($name);
  //config['cacheTime']==0也就是不启用缓存是直接返回数据
  if ($this->config['cacheTime'] <> 0) {
   if($this->config['cacheType']==1){
    $write_data = "<?php exit;?>".serialize($data);
    //return $data;
   }else {
    $write_data = "<?php\\r\\n\\$var= ";
    $write_data .= var_export($data,true);
    $write_data .=";\\r\\n?>";
   }
   $this->cache_write($name,$write_data);
  }
  return $data;
 }
 //缓存文件名
 private function cache_file($filename){
  return $this->config['cacheRoot'].$filename.$this->config['cacheExe'];
 }
 //读取文件
 public function cache_read($file){
  $file=$this->cache_file($file);
  if (!file_exists($file)) {
   return '';
  }
  if($this->config['cacheType']==1){
   if (function_exists('file_get_contents')){
    $cache_Content= file_get_contents($file);
   }else{
    $fopen = fopen($file,'r');
    $cache_Content = '';
    do {
     $data = fread($fopen,filesize($file));
     if (strlen($data)===0) break;
     $cache_Content .= $data;
    }while(1);
    fclose($fopen);
   }
   $cache_Content = substr($cache_Content,13);/* 去除<?php exit;?> */
   $cache_Content = unserialize($cache_Content);
   return $cache_Content;
  }else{
   include_once($file);
   return $var;
  }
 }
 //循环创建目录
 private function makeDir( $dir, $mode = 0777 ) {
  if( ! $dir ) return 0;
  $dir = str_replace( "\\\\", "/", $dir );
  $mdir = "";
  foreach( explode( "/", $dir ) as $val ) {
   $mdir .= $val."/";
   if( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
   if( ! file_exists( $mdir ) ) {
    if(!@mkdir( $mdir, $mode )){
     return false;
    }
   }
  }
  return true;
 }
}
?>

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
PHP技术开发技巧分享
Mar 23 PHP
PHP漏洞全解(详细介绍)
Nov 13 PHP
基于AppServ,XAMPP,WAMP配置php.ini去掉警告信息(NOTICE)的方法详解
May 07 PHP
PHP简单实现“相关文章推荐”功能的方法
Jul 19 PHP
Yii框架中sphinx索引配置方法解析
Oct 18 PHP
php正则表达式基本知识与应用详解【经典教程】
Apr 17 PHP
php实现留言板功能(会话控制)
May 23 PHP
php获取微信共享收货地址的方法
Dec 21 PHP
laravel手动创建数组分页的实现代码
Jun 07 PHP
PHP如何获取Cookie并实现模拟登录
Jul 16 PHP
Laravel统一错误处理为JSON的方法介绍
Oct 18 PHP
如何解决php-fpm启动不了问题
Nov 17 PHP
PHP批量去除BOM头代码分享
Jun 26 #PHP
PHP多态代码实例
Jun 26 #PHP
PHP微信开发之二维码生成类
Jun 26 #PHP
Thinkphp关闭缓存的方法
Jun 26 #PHP
php获取、检查类名、函数名、方法名的函数方法
Jun 25 #PHP
php header函数的常用http头设置
Jun 25 #PHP
PHP里的单例类写法实例
Jun 25 #PHP
You might like
PHP写UltraEdit插件脚本实现方法
2011/12/26 PHP
PHP批量删除、清除UTF-8文件BOM头的代码实例
2014/04/14 PHP
美图秀秀web开放平台--PHP流式上传和表单上传示例分享
2014/06/22 PHP
Smarty模板常见的简单应用分析
2016/11/15 PHP
Thinkphp 中 distinct 的用法解析
2016/12/14 PHP
JS类中定义原型方法的两种实现的区别
2007/03/08 Javascript
jquery如何判断某元素是否具备指定的样式
2013/11/05 Javascript
ExtJS自定义主题(theme)样式详解
2013/11/18 Javascript
基于jQuery的JavaScript模版引擎JsRender使用指南
2014/12/29 Javascript
Angular中的Promise对象($q介绍)
2015/03/03 Javascript
Jquery中map函数的用法
2016/06/03 Javascript
JavaScript简单下拉菜单特效
2016/09/13 Javascript
jQuery图片加载显示loading效果
2016/11/04 Javascript
浅谈javascript中遇到的字符串对象处理
2016/11/18 Javascript
javascript简单进制转换实现方法
2016/11/24 Javascript
ES6使用Set数据结构实现数组的交集、并集、差集功能示例
2017/10/31 Javascript
浅谈在不使用ssr的情况下解决Vue单页面SEO问题(2)
2018/11/08 Javascript
通过js示例讲解时间复杂度与空间复杂度
2019/08/06 Javascript
解决$store.getters调用不执行的问题
2019/11/08 Javascript
Vue+Node实现商品列表的分页、排序、筛选,添加购物车功能详解
2019/12/07 Javascript
JavaScript console的使用方法实例分析
2020/04/28 Javascript
解决vuex改变了state的值,但是页面没有更新的问题
2020/11/12 Javascript
[42:32]DOTA2上海特级锦标赛B组资格赛#2 Fnatic VS Spirit第二局
2016/02/27 DOTA
Python递归函数定义与用法示例
2017/06/02 Python
Python中工作日类库Busines Holiday的介绍与使用
2017/07/06 Python
Python中捕获键盘的方式详解
2019/03/28 Python
什么是Python包的循环导入
2020/09/08 Python
python打包多类型文件的操作方法
2020/09/21 Python
python快速安装OpenCV的步骤记录
2021/02/22 Python
高中生学习总结的自我评价范文
2013/10/13 职场文书
饭店服务员岗位职责
2015/02/09 职场文书
幼儿园百日安全活动总结
2015/05/07 职场文书
教师工作证明范本
2015/06/12 职场文书
团支部组织委员竞选稿
2015/11/21 职场文书
优秀的商业计划书,让融资一步到位
2019/05/07 职场文书
Pytorch 实现变量类型转换
2021/05/17 Python