PHP生成普通的静态文件

<?php 
class File{
    private $_dir;
    //定义缓存文件后缀
    const EXT = '.txt';
    public function __construct(){
        //定义缓存文件生成路径
        $this->_dir = dirname(__FILE__).'/aaaa/';
    }
    /*
    *生成静态缓存
    *@param string $key 缓存文件名
    *@param array $value 缓存内容
    *@param string $path 缓存路径
    */
    public function cacheData($key,$value='',$path=''){
        $filename = $this->_dir.$key.self::EXT;
            if($value!==''){
                //删除缓存文件
                if(is_null($value)){//$value为NULL时,删除缓存文件
                    return @unlink($filename);
                }

                //生成缓存文件
                $dir = dirname($filename);
                if(!is_dir($dir)){//缓存文件路径不存在时,生成文件路径
                    mkdir($dir,0777);
                }
                //file_put_contents($key,$value);$value只能是字符串格式,所以可以序列化一下,生成缓存文件
                return file_put_contents($filename,json_encode($value));
            }
            //读取缓存
            if(!is_file($filename)){
                return false;
            }else{
                return json_decode(file_get_contents($filename,true));
            }
    }
}
$file = new File();
$data = [
    '1'=>'1',
    '2'=>'2'
    ];
//生成缓存
$file->cacheData('cache1',$data);
//读取缓存
$file->cacheData('cache1');
//删除缓存
$file->cacheData('cache1',null);

猜你喜欢

转载自blog.csdn.net/zhao_teng/article/details/80509088