静态缓存

1.file.php

<?php
    class File{
        private $_dir;
        const EXT='.txt';
        public function __construct(){
            $this->_dir=dirname(__FILE__).'/files/';
        }
        public function cacheData($key,$value='',$path=''){
            $filename=$this->_dir.$path.$key.self::EXT;
            if($value!==''){//将value值写入缓存
                if(is_null($value)){
                    return @unlink($filename);
                }
                $dir=dirname($filename);
                if(!is_dir($dir)){
                    //赋予权限
                    mkdir($dir,0777);
                }
                //写入成功返回字节数,写入失败返回false
                return file_put_contents($filename,json_encode($value));
            }
            if(!is_file($filename)){
                return false;
            }else{
                return json_decode(file_get_contents($filename),true);
            }
        }
    }

2.test.php

<?php
require_once('./file.php');
$data=array(
    'id'=>1,
    'name'=>'singwa',
    'type'=>array(4,5,6),
    'test'=>array(1,45,67=>array(123,'tsysa')),
);
$file=new File();
//生成缓存
if($file->cacheData('index_mk_cache',$data)){
    echo "success";
}else{
    echo "error";
}
// 读取缓存
if($file->cacheData('index_mk_cache')){
    echo "<pre/>";
    var_dump($file->cacheData('index_mk_cache'));exit;
    echo "success";
}else{
    echo "error";
}
// 删除缓存
if($file->cacheData('index_mk_cache',null)){
    echo "success";
}else{
    echo "error";
}
原文地址:https://www.cnblogs.com/xiaobiaomei/p/7858091.html