php app接口开发-2

 

 

 

 

 

 

 

 创建fiel.php

 1 <?php
 2 
 3 class File {
 4     private $_dir;
 5 
 6     const EXT = '.txt';
 7 
 8     public function __construct() {
 9         $this->_dir = dirname(__FILE__) . '/files/';
10     }
11     public function cacheData($key, $value = '', $cacheTime = 0) {
12         $filename = $this->_dir  . $key . self::EXT;
13 
14         if($value !== '') { // 将value值写入缓存
15             if(is_null($value)) {
16                 return @unlink($filename);
17             }
18             $dir = dirname($filename);
19             if(!is_dir($dir)) {
20                 mkdir($dir, 0777);
21             }
22 
23             $cacheTime = sprintf('%011d', $cacheTime);
24             return file_put_contents($filename,$cacheTime . json_encode($value));
25         }
26 
27         if(!is_file($filename)) {
28             return FALSE;
29         }
30         $contents = file_get_contents($filename);
31         $cacheTime = (int)substr($contents, 0 ,11);
32         $value = substr($contents, 11);
33         if($cacheTime !=0 && ($cacheTime + filemtime($filename) < time())) {
34             unlink($filename);
35             return FALSE;
36         }
37         return json_decode($value, true);
38 
39     }
40 }
41 
42 $file = new File();
43 
44 echo $file->cacheData('test1');
View Code

 通过test.php调用file.php,访问app_api.com/test.php,生成缓存

 1 <?php
 2 require_once("./file.php");
 3 $data = array(
 4     "name" => "bk",
 5     "age" => 25
 6 );
 7 $file = new File();
 8 if($file->cacheData("index_mk_cache",$data)){
 9     echo "success";
10 }else{
11     echo "error";
12 }
View Code

 

 

 

 在test.php文件获取缓存

 1 <?php
 2 //require_once("./response.php");
 3 //
 4 //$data = array(
 5 //    "name" => "bk",
 6 //    "age" => 25
 7 //);
 8 //
 9 //Response::show(200,"返回成功",$data,"xml");
10 
11 
12 
13 require_once("./file.php");
14 $data = array(
15     "name" => "bk",
16     "age" => 25
17 );
18 $file = new File();
19 if($file->cacheData("index_mk_cache")){
20     var_dump($file->cacheData("index_mk_cache"));exit();
21     echo "success";
22 }else{
23     echo "error";
24 }

效果

在test.php文件删除缓存

 1 <?php
 2 //require_once("./response.php");
 3 //
 4 //$data = array(
 5 //    "name" => "bk",
 6 //    "age" => 25
 7 //);
 8 //
 9 //Response::show(200,"返回成功",$data,"xml");
10 
11 
12 
13 require_once("./file.php");
14 $data = array(
15     "name" => "bk",
16     "age" => 25
17 );
18 $file = new File();
19 if($file->cacheData("index_mk_cache",null)){
20     echo "success";
21 }else{
22     echo "error";
23 }

效果,删除原来创建的缓存文件

 

posted @ 2020-04-20 18:38  一个勤奋的程序员  阅读(210)  评论(0编辑  收藏  举报