PHP · 2009年8月14日 0

写了个文件缓存类,记录下

<?php
/**
 * 文件缓存类
 *
 * @author 废墟
 * @version v1.01 2009-08-18
 * @link http://anerg.cn/
 */
class cache {
    private $cache_time;
    private $cache_dir;

    public function __construct($cache_dir = './cache/', $cache_time = 3600) {
        $this->cache_time    = $cache_time;
        $this->cache_dir    = $cache_dir;
    }

    public function set_cache_dir($cache_dir) {
        $this->cache_dir    = $cache_dir;
    }

    public function set_cache_time($cache_time) {
        $this->cache_time    = $cache_time;
    }

    public function get_cache($cache_file) {
        $_CACHE = array();
        $filename = $this->cache_dir.'/'.$cache_file.".cache.php";

        if(!file_exists($filename) || time() - filemtime($filename) > $this->cache_time) {
            return false;
        } else {
            return unserialize(file_get_contents($filename));
        }
    }

    public function set_cache($cache_file,$data) {
        $filename = $this->cache_dir.'/'.$cache_file.".cache.php";
        if( $this->mkpath($this->cache_dir) ) {
            $out    = serialize($data);
            file_put_contents($filename, $out);
        }
    }

    public function del_cache($cache_file) {
        return unlink($this->cache_dir.'/'.$cache_file.".cache.php");
    }

    public function mkpath($dir) {
        return is_dir($dir) or ($this->mkpath(dirname($dir)) and (mkdir($dir, 0777) and chmod($dir,0777)));
    }
}
//
//$cache = new cache();
//$cache->set_cache_dir('./cache/ss/ff/mm/');
//$cache->set_cache_time(10);
//$cache_file    = '321ewqe3412132';
//$data    = array("1ee"=>"teseweq222ewt");
//$cache->set_cache($cache_file, $data);
//print_r($cache->get_cache($cache_file));
?>