1. 程式人生 > >PHP操作靜態快取

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";
}