温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php缓存机制的实现方式

发布时间:2021-07-26 10:48:04 来源:亿速云 阅读:88 作者:chen 栏目:开发技术

本篇内容主要讲解“php缓存机制的实现方式”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php缓存机制的实现方式”吧!

复制代码 代码如下:


<?php
class Cache
{
 private $dir = "data/cache/";//定义缓存目录 
 private $key='c_a_sss'; // 文件名md5加密密钥

 function set_dir($dirpath)
 {
  $this->dir=$dirpath;
  $this->make_dir($this->dir);
 }
 function read($key,$minutes=1)
 {
  $filename=$this->get_filename($key);
  if($datas = @file_get_contents($filename))
  {
    $datas = unserialize($datas);
    if(time() - $datas['time'] < $minutes*60)
    {
     return $datas['data'];
    }
  }
  return false;
 }

 function write($key,$data)
 {  
  $filename=$this->get_filename($key);
  if($handle = fopen($filename,'w+'))
  {
   $datas = array('data'=>$data,'time'=>time());
   flock($handle,LOCK_EX);
   $rs = fputs($handle,serialize($datas));
   flock($handle,LOCK_UN);
   fclose($handle);
   if($rs!==false){return true;  }
  }
  return false;
 }
 function clear_all()
 {
  $dir=$this->dir;
  $this->del_file($dir); 
 }

  private function get_filename($key)
 {
  return $this->dir.$key.'_'.md5($key.$this->key);
 }
 private function make_dir($path)
 {
  if (! file_exists ( $path ))
  {
   $this->make_dir ( dirname ( $path ) );
   if (! mkdir ( $path, 0777 ))
   die ( '无法创建缓存文件夹' . $path );
  }
 }
 private function del_file($dir)
 {
  if (is_dir($dir))
  {
   $dh=opendir($dir);//打开目录 //列出目录中的所有文件并去掉 . 和 ..
   while (false !== ( $file = readdir ($dh))) {
    if($file!="." && $file!="..") {
     $fullpath=$dir."/".$file;
     if(!is_dir($fullpath)) {
      unlink($fullpath);
     } else {
      $this->del_file($fullpath);
     }
    }
   }
   closedir($dh);
  }
 }
}

$cache = new cache();
  $cache->set_dir('data/cache_dir/');
  $data=$cache->read('sys',1);
  if(empty($data))
  {
   $data=array('aa'=>1111,'bb'=>2222,'date'=>date('Y-m-d H:i:s'));
   $cache->write('sys',$data); 
  }
  print_r($data);

到此,相信大家对“php缓存机制的实现方式”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI