闲着无聊写着玩,最主要原因是博客好久没更新内容,也就是凑合更新点内容,哈哈!言归正传
代码如下:

<?php
	error_reporting(0);
	header("Content-Type:text/html; charset=UTF-8");
	class File{
		private $_dir;
		const suffix='.txt';
		public function __construct(){
			//默认的缓存文件存放路径
			$this->_dir=dirname(__FILE__).'/cache/';
		}

		/**
		**缓存文件的写入,获取,删除!
		**@params  $key     缓存文件的文件名
		**@params  $value   缓存数据
		**@params  $path    路径
		**/
		public function cacheDate($key,$value='',$path=''){
			//拼装成一个文件
			$filename=$this->_dir.$path.$key.self::suffix;
			if($value!==''){//将value值写入缓存
				//如果值为null的时候,就删除文件
				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);
			}
		}
	}

    $data = array('id'=>1,'name'=>'运达blog','age'=>25,'like'=>'游泳,旅游');
    $list = new File();
     
    //获取缓存文件数据
    if($list->cacheDate('cache_file')==null){
    	echo "缓存文件不存在或者缓存数据为空!".'<br/>';
    }else{
    	var_dump($list->cacheDate('cache_file'));
    }

    //生成缓存文件
    if($list->cacheDate('cache_file',$data)){
    	echo "数据缓存成功!";
    }else{
    	echo "数据缓存失败!";
    }

    //数据为null的时候,删除缓存文件
    if($list->cacheDate('cache_file',null)){
    	echo "删除缓存文件成功!";
    }else{
    	echo "删除缓存文件失败!";
    }

?>

转载请注明转自:运达's blog 原文地址:http://www.yunda51.com/1653.html