APP接口开发--对静态缓存文件生成缓存失效时间

<?php
class File
{
	private $_dir;
	const EXT = '.txt';

	public function __construct()
	{
		$this->_dir = dirname(__FILE__).'\files\/';
	}

	public function cacheData($path='',$value='',$cacheTime=0)
	{
		$filename = $this->_dir.$path.self::EXT;
		if($value !==''){

			//删除静态缓存文件
			if(is_null($value)){
				return @unlink($filename);				
			}
		
			//dirname() 返回路径中的目录部分 D:\phpstudy_pro\WWW\test\files
			$dir = dirname($filename);
			if(!is_dir($dir)){ //判读文件目录是否存在
				mkdir($dir,0777);
			}

			//格式化的字符串写入一个变量中 将缓存失效时间写入文件中
			$cacheTime = sprintf('%011d',$cacheTime);
			//file_put_contents() 写入文件内容
			return file_put_contents($filename,$cacheTime.json_encode($value));
		}

		//读取静态文件内容
		if(!is_file($filename)){//判断静态文件是否存在
			return false;
		}else{
			//file_get_contents()  读取文件内容
			$connects = file_get_contents($filename);
			//将缓失效时间截取
			$cacheTime = substr($connects,0,11);
			//获取缓存内容
			$value = substr($connects,11);

			//根据 生成文件时间+缓存文件时间 < 当前时间 条件成立则删除缓存文件
			if($cacheTime !=0 && $cacheTime+fileatime($filename) < time()){
				unlink($filename);
				return false;
			}
			return json_decode($value,true);
		}
	}		
}





$file = new File;
//测试数据
$arr = array(
	'a'=>11111,
	'b'=>3333
);

//写入缓存 并设置缓存失效时间为120秒
// $file->cacheData('test',$arr,120);

// //读取文件内容
echo "<pre>";
var_dump($file->cacheData('test'));

//删除静态缓存文件
// var_dump($file->cacheData('test',NULL));
发布了40 篇原创文章 · 获赞 0 · 访问量 678

猜你喜欢

转载自blog.csdn.net/weixin_39218464/article/details/104074878
今日推荐