Home > Article > Backend Development > Develop Android server using php to create dynamic cache_PHP tutorial
3. Delete cache
Generate cache file:
file.php operates static cache classes
<?php class File {//操作静态缓存的业务 private $_dir; const EXT = '.txt'; public function __construct() { //获取文件当前目录,把缓存文件放到当前目录files下 $this->_dir = dirname(__FILE__) . '/files/'; } //key是缓存文件文件名,value是缓存数据 public function cacheData($key, $value = '', $path='') { $filename = $this->_dir . $path . $key . self::EXT; if($value !== '') { // 将value值写入缓存 //获取目录,判断如果目录不存在,创建目录 $dir = dirname($filename); if(!is_dir($dir)) { mkdir($dir, 0777);//生成目录,给出权限 } //第一个参数文件名,第二个数据(String),把数组vlaue转换成字符串 return file_put_contents($filename,json_encode($value)); } } }
<?php require_once('./file.php'); $data=array( 'id'=>1, 'name'=>'david', 'type'=>array(4,5,6) ); $file=new File(); if($file->cacheData('davidcache',$data)){ echo "success";}else{ echo "error"; }
If the generation is successful, success
will be displayed.This creates a cache file named davidchche.txt in the file directory of the current file directory.
Advanced version: also implements cache reading and deletion
file.php
<?php class File {//操作静态缓存的业务 private $_dir; const EXT = '.txt'; public function __construct() { //获取文件当前目录,把缓存文件放到当前目录files下 $this->_dir = dirname(__FILE__) . '/files/'; } //key是缓存文件文件名,value是缓存数据 public function cacheData($key, $value = '', $path='') { $filename = $this->_dir . $path . $key . self::EXT; if($value !== '') { // 将value值写入缓存 if(is_null($value)) {//如果value值穿null则删除这个缓存文件 return @unlink($filename); } //获取目录,判断如果目录不存在,创建目录 $dir = dirname($filename); if(!is_dir($dir)) { mkdir($dir, 0777);//生成目录,给出权限 } //第一个参数文件名,第二个数据(String),把数组vlaue转换成字符串 return file_put_contents($filename,json_encode($value)); } if(!is_file($filename))//读取缓存文件 { return FALSE; }else{ return json_decode(file_get_contents($filename),true); } } }
testfile.php
<?php require_once('./file.php'); $data=array( 'id'=>1, 'name'=>'david', 'type'=>array(4,5,6) ); $file=new File(); //删除缓存文件 if($file->cacheData('davidcache',null)){ //if($file->cacheData('davidcache')){ //var_dump($file->cacheData('davidcache')); //exit; echo "success";}else{ echo "error"; } /*下面这个是读取缓存时使用的 if($file->cacheData('davidcache')){ var_dump($file->cacheData('davidcache')); exit; echo "success";}else{ echo "error"; }*/ /*下面这个是创建缓存调用的 if($file->cacheData('davidcache',$data)){ echo "success";}else{ echo "error"; }*/ //根据file类,如果value为空='',读取缓存数据, //如果value为null,删除缓存数据, //如果value不为空,也不是null,那么创建缓存数据