美文网首页
【PHP】---静态缓存 实例

【PHP】---静态缓存 实例

作者: 小气的王二狗 | 来源:发表于2018-03-21 20:33 被阅读12次

    index.php

    <?php
    require 'catchFile.php';
    $data=array(
      'name'=>'wlc',
      'age'=>'22',
      'sid'=>'1275591716'
    );
    $file= new File();
    // if($file->catchData('json',$data,'demo/')){
    //     echo "存入成功!";
    // }else{
    //   echo "出现错误!";
    // }
    // echo "<pre>";
    
      //print_r($file->catchData('json','','demo/')) ;读取文件中的json
    $file->catchData('json',null,'demo/');
    
    

    catchFile.php

    <?php
    /**
     *
     */
    class File
    {
      private $_dir;//当前目录
      const EXT='.txt';//写入文件的文件后缀
      //构造方法
      function __construct()
      {
        $this->_dir=dirname(__FILE__)."/files/";//dirname()方法获取当前目录
      }
      public function catchData($key,$value='',$path='')//$key相当于文件名
      {
        $filename=$this->_dir.$path.$key.self::EXT;
        echo $filename;
        //echo is_null($value);
        if(is_null($value)){
          unlink($filename);
        }
        //echo json_encode($value);
      //  echo $dir=dirname($filename);
          //print_r(json_decode(file_get_contents($filename),true));
        if($value!=''){//将value写入缓存
    
          $dir=dirname($filename);//$dir 为写入文件的
          if(!is_dir($dir)){//判断这个目录是否存在
            mkdir($dir,0777);//如果不存在,创建这个目录
          }else{
            file_put_contents($filename,json_encode($value));
            return true;
          }
        }
        if(!is_file($filename)){
          return false;
    
        }else{
    
          return json_decode(file_get_contents($filename),true);
        }
      }
    }
    
    

    相关文章

      网友评论

          本文标题:【PHP】---静态缓存 实例

          本文链接:https://www.haomeiwen.com/subject/lwmwqftx.html