php简单缓存类

<?php
class Cache {
    private $cache_path;//path for the cache
    private $cache_expire;//seconds that the cache expires

    //cache constructor, optional expiring time and cache path
    public function Cache($exp_time=3600,$path){
        $this->cache_expire=$exp_time;
        $this->cache_path=$path;
        $this->CreateFolder($path);
    }

    //returns the filename for the cache
    private function fileName($key){
        return $this->cache_path.$key;
    }

    //creates new cache files with the given data, $key== name of the cache, data the info/values to store
    public function put($key, $data){
        $values = serialize($data);
        $filename = $this->fileName($key);
        $file = fopen($filename, 'w');
        if ($file){//able to create the file
            fwrite($file, $values);
            fclose($file);
        }
        else return false;
    }

    //returns cache for the given key
    public function get($key){
        $filename = $this->fileName($key);
        if (!file_exists($filename) || !is_readable($filename)){//can't read the cache
            return false;
        }
        if ( time() < (filemtime($filename) + $this->cache_expire) ) {//cache for the key not expired
            $file = fopen($filename, "r");// read data file
            if ($file){//able to open the file
                $data = fread($file, filesize($filename));
                fclose($file);
                return unserialize($data);//return the values
            }
            else return false;
        }
        else return false;//was expired you need to create new
     }
    public  function CreateFolder($dir, $mode = 0777){
        if (is_dir($dir) || @mkdir($dir, $mode))
            return true;
        if (!self::CreateFolder(dirname($dir), $mode))
            return false;
        return @mkdir($dir, $mode);
    }
}
?>

用法如下:

<?php

   include 'cache.class.php'; //引入缓存类

   $cache_time = '86400'; //设置缓存时间

   $cache_path = 'cache/';  //设置缓存路径

   $cache_filename = 'cachefile';  //设置缓存文件名

   $cache = new Cache($cache_time,$cache_path); //实例化一个缓存类
        $key = $cache_filename;
        $value = $cache->get($key);
        if ($value == false) {
            $value = getDataFromDb();  //getDataFromDb是从数据库中读取数据的函数
            $cache->put($key, $value); //写入缓存
        }


        得到$value就是想要的数据 ,根据需求自己写方法。

?>

转载于:https://www.cnblogs.com/kwishly/p/3491189.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值