PHP操作静态缓存

视屏:https://www.imooc.com/video/2808

新建File.php文件

<?php
/**
 * @Author: Marte
 * @Date:   2018-10-08 20:05:37
 * @Last Modified by:   Marte
 * @Last Modified time: 2018-10-08 21:05:27
 * @param key string 缓存文件的文件名
 * @param value String 缓存文件
 * @param $path String 缓存路劲
 */
class File{
    private $_dir;
    const EXT='.txt';
    public function __construct(){
        $this->_dir=dirname(__FILE__).'/files/';
    }
    public  function OperationCache($key,$value='',$path=''){
        $filename=$this->_dir.$path.$key.self::EXT;
        if($value!==''){
            if (is_null($value)) {
                return @unlink($filename);
            }
            $dir=dirname($filename);
            if(!is_dir($dir)){
                mkdir($dir,0777);
            }
            return file_put_contents($filename,json_encode($value));
        }
        if (!is_file($filename)) {
            return false; 
        }else{
            return json_decode(file_get_contents($filename),true);
        }
    }
} 

 测试文件

test.php

<?php
/**
 * @Author: Marte
 * @Date:   2018-10-08 20:37:57
 * @Last Modified by:   Marte
 * @Last Modified time: 2018-10-08 22:33:56
 */
require_once("./File.php");
$data=array(
 'id'=>100,
    'age'=>30,
    'type'=>'sex',
    'test'=>array(1,2,3,4),
    );

$file=new File();
if($file->OperationCache('index',null)){
    //var_dump($file->OperationCache('index'));exit;
    echo "success";
}else{
    echo "error";
}

猜你喜欢

转载自blog.csdn.net/qq_36447759/article/details/82975347