凌的博客

您现在的位置是: 首页 > 学无止境 > PHP > 

PHP

php文件缓存类

2015-05-14 PHP 752
/** * 文件类型缓存类 */ class Cache { public $options; /** * 架构函数 * @access public */ public function __construct($options=array()) { $options[\'path\'] = defined(CACHE
/**
 * 文件类型缓存类
 */
class Cache {
	public $options;
    /**
     * 架构函数
     * @access public
     */
    public function __construct($options=array()) {
		$options['path'] = defined(CACHE_PATH) ? CACHE_PATH : './cache';
		$options['expire'] = defined(CACHE_TIME) ? CACHE_TIME : 5;
		
		$this->options = $options;
    }

    /**
     * 取得变量的存储文件名
     * @access private
     * @param string $name 缓存变量名
     * @return string
     */
    private function filename($name){
		$name = trim($name);
		if(!empty($name)){
			return $this->options['path'].'/'.$name.'.cache.php';	
		}else{
			$this->halt('文件名不存在');
		}
    }

    /**
     * 读取缓存
     * @access public
     * @param string $name 缓存变量名
     * @return mixed
     */
    public function get($name) {
		$ret = $this->_get($name);
		//过期清除
		if($ret['expire_time']!=0 && $ret['expire_time'] < time()){
			$this->rm($name);
		}
		return $ret['data'];
    }

    /**
     * 读取缓存
     * @access private
     * @param string $name 缓存变量名
     * @return mixed
     */
    private function _get($name) {
		$content =file_get_contents( $this->filename($name) );
		$ret = explode("\n",$content,2);
		$data = preg_replace("/^return \'/",'',$ret[1]);
		$data = preg_replace("/\';$/",'',$data);
		return array(
			'expire_time' => str_replace(' unserialize($data),
		);
    }

    /**
     * 写入缓存
     * @access public
     * @param string $name 缓存变量名
     * @param mixed $value  存储数据
     * @param int $expire  有效时间 0为永久
     * @return boolean
     */
    public function set($name,$value,$expire=0) {
		//检查目录是否存在 不存在创建
		if(!file_exists($this->options['path'])){
			@mkdir($this->options['path'],0777,true);	
		}
		//准备缓存数据
		$data = serialize($value);
		$content = 'options['expire'] >0 ? time()+$this->options['expire'] : 0)."\nreturn '".$data."';";
		//存储文件
		return file_put_contents($this->filename($name),$content);
    }

    /**
     * 删除缓存
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public function rm($name) {
        return unlink($this->filename($name));
    }

    /**
     * 清除缓存
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public function clear($name) {
        return unlink($this->filename($name));
    }
	
	/**
	* 显示错误信息
	*/
	public function halt($msg){
		echo 'Cache Error:'.$msg;
		exit;
	}
}

/**
*文件缓存
*@param string $key 键值
*@param mix $value 缓存的数据
*@param int $expire 缓存时间 单位秒(s)
*/
function F($key,$value=false,$expire=false){
	$Cache = new Cache();
	if($value !==false){
		if($expire !== false){
			return $Cache->set($key,$value,$expire);
		}else{
			return $Cache->set($key,$value);
		}
	}else{
		return $Cache->get($key);	
	}
}

文章评论

0条评论