侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

php文件缓存方法总结

php  /  管理员 发布于 7年前   170

为大家分享很全的php文件缓存,供大家参考,具体内容如下

 "./",  'file_name_prefix' => 'cache',  'mode'   => '1', //mode 1 为serialize model 2为保存为可执行文件 );   /**  * 得到本类实例  *   * @return Ambiguous  */ public static function getInstance() {  if(self::$_instance === null)  {   self::$_instance = new self();  }  return self::$_instance; }   /**  * 得到缓存信息  *   * @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; }  /**  * 设置一个缓存  *   * @param string $id 缓存id  * @param array $data 缓存内容  * @param int $cacheLife 缓存生命 默认为0无限生命  */ 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); }  /**  * 清除一条缓存  *   * @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); }  /**  * 判断缓存是否存在  *   * @param string $id cache_id  * @return boolean true 缓存存在 false 缓存不存在  */ public static function has($id) {  $instance = self::getInstance();  $file  = $instance->_file($id);    if(!is_file($file))  {   return false;  }  return true; }  /**  * 通过缓存id得到缓存信息路径  * @param string $id  * @return string 缓存文件路径  */ protected function _file($id) {  $instance = self::getInstance();  $fileNmae = $instance->_idToFileName($id);  return $instance->_options['cache_dir'] . $fileNmae; }   /**  * 通过id得到缓存信息存储文件名  *   * @param $id  * @return string 缓存文件名  */ 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); }  /**  * 把数据写入文件  *   * @param string $file 文件名称  * @param array $contents 数据内容  * @return bool   */ protected function _filePutContents($file, $contents) {  if($this->_options['mode'] == 1)  {   $contents = serialize($contents);  }  else   {   $time = time();    $contents = "";  }    $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;     }  /**  * 从文件得到数据  *   * @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;  } }  /**  * 构造函数  */ protected function __construct() {  }  /**  * 设置缓存路径  *   * @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; }  /**  * 设置缓存文件前缀  *   * @param srting $prefix  * @return self  */ public static function setCachePrefix($prefix) {  $instance = self::getInstance();  $instance->_options['file_name_prefix'] = $prefix;  return $instance; }  /**  * 设置缓存存储类型  *   * @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; }  /**  * 删除所有缓存  * @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 缓存存储方式/*   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

 './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; }   /**  * 设置参数  * @param array $options 缓存参数  * @return void  */ static function &setOptions($options = array()) {   return self::getInstance($options); }   /**  * 构造函数  * @param array $options 缓存参数  * @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 不能为空 ');  } }  /**  * 设置缓存路径  * @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; }   /**  * 存入缓存数据  * @param array $data   放入缓存的数据  * @param string $id   缓存id(又名缓存识别码)  * @param cache_life   缓存时间  * @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 = ""    ;     $res = $self->_filePutContents($file, $data);  return $res; }     /**  * 得到缓存信息  *  * @param string $id 缓存id  * @return string|array 缓存数据  */ static function load($id) {  $self = & self::getInstance();  $time = time();  //检测缓存是否存在  if (!$self->test($id)) {   // The cache is not hit !   return false;  }     //全部清空识别文件  $clearFile = $self->_file(self::CLEAR_ALL_KEY);     $file = $self->_file($id);     //判断缓存是否已被全部清除  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; }    /**  * 写入缓存文件  *  * @param string $file 缓存路径  * @param string $string 缓存信息  * @return boolean true 成功  */ 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; }   /**  * 格式化后的缓存文件路径  *  * @param string $id 缓存id  * @return string 缓存文件名(包括路径)  */ protected function _file($id) {  $self = & self::getInstance();  $fileName = $self->_idToFileName($id);  return $self->_options['cache_dir'] . $fileName; }    /**  * 格式化后的缓存文件名字  *  * @param string $id 缓存id  * @return string 缓存文件名  */ 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; }   /**  * 得到缓存信息  *  * @param string $file 缓存路径  * @return string 缓存内容  */ protected function _fileGetContents($file) {  if (!is_file($file)) {   return false;  }  return include $file; }     /**  * 清除所有缓存  *   * @return void  */  static function clear() {  $self = & self::getInstance();  $self->save('CLEAR_ALL',self::CLEAR_ALL_KEY);  }    /**  * 清除一条缓存  *   * @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); } }

存入数据

 'xiaojiong', 'qq' => '290747680', 'age' => '20',);//第一个参数 缓存data//第二个参数 缓存id//第三个参数 cache_life 0 永不过期(cache::clear()清空所有除外) 默认cache_life 为option_cache_lifecache::save($config,'config',0);

载入数据

清空缓存

cache信息配置

//在执行所有cache_func前调用$_options = array( 'cache_dir' => './cache', //缓存文件目录 'file_name_prefix' => 'cache',//缓存文件前缀 'file_life' => 100000, //缓存文件生命);cache::setOptions($options);//再执行 就会按着新配置信息执行,否则是默认信息cache::save($arr,'arr');//就是这个方法 貌似不合理 望大家指点

以上就是本文的全部内容,希望对大家的学习有所帮助。

您可能感兴趣的文章:

  • PHP编程风格规范分享
  • php 中的4种标记风格介绍
  • 关于PHPDocument 代码注释规范的总结
  • PHP常用技巧总结(附函数代码)
  • php代码优化及php相关问题总结
  • 浅析PHP7新功能及语法变化总结
  • PHP中读取文件的几个方法总结(推荐)
  • 学习PHP的数组总结【经验】
  • 关于php中一些字符串总结
  • PHP缓冲区用法总结
  • php好代码风格的阶段性总结


  • 上一条:
    关于PHP中Session文件过多的问题及session文件保存位置
    下一条:
    php常用图片处理类
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客