首页 php教程 PHP源码 php 文件缓存

php 文件缓存

May 25, 2016 pm 05:13 PM

php 文件缓存

<?php 
class cache
{	
	private static $_instance = null;

    protected $_options = array(
        &#39;cache_dir&#39;        => "./",
        &#39;file_name_prefix&#39; => &#39;cache&#39;,
    	&#39;mode&#39;            => &#39;1&#39;, //mode 1 为serialize model 2为保存为可执行文件
    );	
	
	/**
	 * 得到本类实例
	 * 
	 * @return Ambiguous
	 */
	public static function getInstance()
	{
		if(self::$_instance === null)
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	} 
	
	/**
	 * 得到缓存信息
	 * 
	 * @param string $id
	 * @return boolean|array
	 */
	public static function get($id)
	{
		$instance = self::getInstance();
		
		//缓存文件不存在
		if(!$instance->has($id))
		{
			return false;
		}
		
		$file = $instance->_file($id);
		
		$data = $instance->_fileGetContents($file);
		
		if($data[&#39;expire&#39;] == 0 || time() < $data[&#39;expire&#39;])
		{
			return $data[&#39;contents&#39;];
		}
		return false;
	}
	
	/**
	 * 设置一个缓存
	 * 
	 * @param string $id   缓存id
	 * @param array  $data 缓存内容
	 * @param int    $cacheLife 缓存生命 默认为0无限生命
	 */
	public static function set($id, $data, $cacheLife = 0)
	{
		$instance = self::getInstance();
		
		$time = time();
		$cache 		   = array();
		$cache[&#39;contents&#39;] = $data;
		$cache[&#39;expire&#39;]   = $cacheLife === 0 ? 0 : $time + $cacheLife;
		$cache[&#39;mtime&#39;]    = $time;
		
		$file = $instance->_file($id);
		
		return $instance->_filePutContents($file, $cache);
	}
	
    /**
     * 清除一条缓存
     * 
     * @param string cache id	 
     * @return void
     */   
	public static function delete($id)
	{
		$instance = self::getInstance();
		
		if(!$instance->has($id))
		{
			return false;
		}
    	$file = $instance->_file($id);
    	//删除该缓存
    	return unlink($file);
	}
	
	/**
	 * 判断缓存是否存在
	 * 
	 * @param string $id cache_id
	 * @return boolean true 缓存存在 false 缓存不存在
	 */
	public static function has($id)
	{
		$instance = self::getInstance();
		$file     = $instance->_file($id);
		
		if(!is_file($file))
		{
			return false;
		}
		return true;
	}
	
	/**
	 * 通过缓存id得到缓存信息路径
	 * @param string $id
	 * @return string 缓存文件路径
	 */
	protected function _file($id)
	{
		$instance  = self::getInstance();
		$fileNmae  = $instance->_idToFileName($id);
		return $instance->_options[&#39;cache_dir&#39;] . $fileNmae;
	}	
	
	/**
	 * 通过id得到缓存信息存储文件名
	 * 
	 * @param  $id
	 * @return string 缓存文件名
	 */
	protected function _idToFileName($id)
	{
		$instance  = self::getInstance();
		$prefix    = $instance->_options[&#39;file_name_prefix&#39;];
		return $prefix . &#39;---&#39; . $id;
	}
	
	/**
	 * 通过filename得到缓存id
	 * 
	 * @param  $id
	 * @return string 缓存id
	 */
	protected function _fileNameToId($fileName)
	{
		$instance  = self::getInstance();
		$prefix    = $instance->_options[&#39;file_name_prefix&#39;];
		return preg_replace(&#39;/^&#39; . $prefix . &#39;---(.*)$/&#39;, &#39;$1&#39;, $fileName);
	}
	
	/**
	 * 把数据写入文件
	 * 
	 * @param string $file 文件名称
	 * @param array  $contents 数据内容
	 * @return bool 
	 */
	protected function _filePutContents($file, $contents)
	{
		if($this->_options[&#39;mode&#39;] == 1)
		{
			$contents = serialize($contents);
		}
		else 
		{
			$time = time();	
	        $contents = "<?php\n".
	                " // mktime: ". $time. "\n".
	                " return ".
	                var_export($contents, true).
	                "\n?>";
		}
		
		$result = false;
	    $f = @fopen($file, &#39;w&#39;);
        if ($f) {
            @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $contents);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
		@chmod($file,0777);
		return $result;				
	}
	
	/**
	 * 从文件得到数据
	 * 
	 * @param  sring $file
	 * @return boolean|array
	 */
	protected function _fileGetContents($file)
	{
		if(!is_file($file))
		{
			return false;
		}
		
		if($this->_options[&#39;mode&#39;] == 1)
		{
			$f = @fopen($file, &#39;r&#39;); 
			@$data = fread($f,filesize($file));
			@fclose($f);
			return unserialize($data);
		}
		else
		{
			return include $file;
		}
	}
	
	/**
	 * 构造函数
	 */
	protected function __construct()
	{
	
	}
	
	/**
	 * 设置缓存路径
	 * 
	 * @param string $path
	 * @return self
	 */
	public static function setCacheDir($path)
	{
		$instance  = self::getInstance();
        if (!is_dir($path)) {
            exit(&#39;file_cache: &#39; . $path.&#39; 不是一个有效路径 &#39;);
        }
        if (!is_writable($path)) {
            exit(&#39;file_cache: 路径 "&#39;.$path.&#39;" 不可写&#39;);
        }
    
        $path = rtrim($path,&#39;/&#39;) . &#39;/&#39;;
        $instance->_options[&#39;cache_dir&#39;] = $path;
        
        return $instance;
	}
	
	/**
	 * 设置缓存文件前缀
	 * 
	 * @param srting $prefix
	 * @return self
	 */
	public static function setCachePrefix($prefix)
	{
		$instance  = self::getInstance();
		$instance->_options[&#39;file_name_prefix&#39;] = $prefix;
		return $instance;
	}
	
	/**
	 * 设置缓存存储类型
	 * 
	 * @param int $mode
	 * @return self
	 */
	public static function setCacheMode($mode = 1)
	{
		$instance  = self::getInstance();
		if($mode == 1)
		{
			$instance->_options[&#39;mode&#39;] = 1;
		}
		else
		{
			$instance->_options[&#39;mode&#39;] = 2;
		}
		
		return $instance;
	}
	
	/**
	 * 删除所有缓存
	 * @return boolean
	 */
	public static function flush()
	{
		$instance  = self::getInstance();
   $glob = @glob($instance->_options[&#39;cache_dir&#39;] . $instance->_options[&#39;file_name_prefix&#39;] . &#39;--*&#39;);
		
		if(empty($glob))
		{
			return false;
		}
		
		foreach ($glob as $v)
		{
			$fileName = basename($v);
			$id =  $instance->_fileNameToId($fileName);
			$instance->delete($id);
		}
		return true;
	}
}

/* 初始化设置cache的配置信息什么的 */
cache::setCachePrefix(&#39;core&#39;); //设置缓存文件前缀
cache::setCacheDir(&#39;./cache&#39;); //设置存放缓存文件夹路径

//模式1 缓存存储方式
//a:3:{s:8:"contents";a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:34;i:4;i:5;i:5;i:6;i:6;i:6;}s:6:"expire";
i:0;s:5:"mtime";i:1318218422;}
//模式2 缓存存储方式
/*
 <?php
 // mktime: 1318224645
 return array (
  &#39;contents&#39; => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 34,
    4 => 5,
    5 => 6,
    6 => 6,
  ),
  &#39;expire&#39; => 0,
  &#39;mtime&#39; => 1318224645,
)
?>
 * 
 * 
 */
cache::setCacheMode(&#39;2&#39;); 

if(!$row = cache::get(&#39;zj2&#39;))
{
	
	$array = array(1,2,3,34,5,6,6);
	$row = cache::set(&#39;zj2&#39;,$array);
}
// cache::flush(); 清空所有缓存

print_r($row);
登录后复制

2. [代码]文件缓存 class

<?php
/**
 * 文件缓存类
 * @author  xiaojiong & 290747680@qq.com
 * @date 2011-08-17
 */
class cache
{
	const FILE_LIFE_KEY = &#39;FILE_LIFE_KEY&#39;;
	
	const CLEAR_ALL_KEY = &#39;CLEAR_ALL&#39;;
	
    static $_instance = null;
	
    protected $_options = array(
        &#39;cache_dir&#39; => &#39;./cache&#39;,
        &#39;file_locking&#39; => true,
        &#39;file_name_prefix&#39; => &#39;cache&#39;,
        &#39;cache_file_umask&#39; => 0777,
    	&#39;file_life&#39;  => 100000
    );
    
    static function &getInstance($options = array())
    {
    	if(self::$_instance === null)
    	{
    		self::$_instance = new self($options);
    	}	
    	return self::$_instance;
    }
    
    /**
     * 设置参数
     * @param  array $options 缓存参数
     * @return void
     */
	static function &setOptions($options = array())
	{
    	    return self::getInstance($options);
	}
	
    /**
     * 构造函数
     * @param  array $options 缓存参数
     * @return void
     */
    private function __construct($options = array())
    {		
        if ($this->_options[&#39;cache_dir&#39;] !== null) {
			
			$dir = rtrim($this->_options[&#39;cache_dir&#39;],&#39;/&#39;) . &#39;/&#39;;
	        $this->_options[&#39;cache_dir&#39;] = $dir;
	        
			if (!is_dir($this->_options[&#39;cache_dir&#39;])) {
	            mkdir($this->_options[&#39;cache_dir&#39;],0777,TRUE);
	        }
	        if (!is_writable($this->_options[&#39;cache_dir&#39;])) {
	            exit(&#39;file_cache: 路径 "&#39;. $this->_options[&#39;cache_dir&#39;] .&#39;" 不可写&#39;);
	        }
	     
        } else {
           exit(&#39;file_cache: "options" cache_dir 不能为空 &#39;);
        }
    }

    /**
     * 设置缓存路径
     * @param  string  $value
     * @return void
     */
    static function setCacheDir($value)
    {
    	$self = & self::getInstance();
    	
        if (!is_dir($value)) {
            exit(&#39;file_cache: &#39; . $value.&#39; 不是一个有效路径 &#39;);
        }
        if (!is_writable($value)) {
            exit(&#39;file_cache: 路径 "&#39;.$value.&#39;" 不可写&#39;);
        }
    
        $value = rtrim($this->_options[&#39;cache_dir&#39;],&#39;/&#39;) . &#39;/&#39;;
        
        $self->_options[&#39;cache_dir&#39;] = $value;
    }
    
    /**
     * 存入缓存数据
     * @param  array  $data          放入缓存的数据
     * @param  string $id            缓存id(又名缓存识别码)
     * @param  cache_life            缓存时间
     * @return boolean True if no problem
     */
    static function save($data, $id = null, $cache_life = null)
    {
    	$self = & self::getInstance();
        if (!$id) {
            if ($self->_id) {
                $id = $self->_id;
            } else {
                exit(&#39;file_cache:save() id 不能为空!&#39;);
            }
        }
        $time = time();
        
        if($cache_life)	{
        	$data[self::FILE_LIFE_KEY] = $time + $cache_life;
        }
		elseif
		($cache_life != 0){
        	$data[self::FILE_LIFE_KEY] = $time + $self->_options[&#39;file_life&#39;];
        }
        
        $file = $self->_file($id);
        
        $data = "<?php\n".
                " // mktime: ". $time. "\n".
                " return ".
                var_export($data, true).
                "\n?>"
                ;
        
        $res = $self->_filePutContents($file, $data);
        return $res;
    }
    
    
    /**
     * 得到缓存信息
     *
     * @param  string  $id  缓存id
     * @return string|array 缓存数据
     */
    static function load($id)
    {
        $self = & self::getInstance();
    	$time = time();
    	//检测缓存是否存在
    	if (!$self->test($id)) {
            // The cache is not hit !
            return false;
        }
        
		//全部清空识别文件
        $clearFile = $self->_file(self::CLEAR_ALL_KEY);
		
		$file = $self->_file($id);
		
        //判断缓存是否已被全部清除
    	if(is_file($clearFile) && filemtime($clearFile) > filemtime($file))
    	{
    		return false;
    	}
       
        $data = $self->_fileGetContents($file);
     	if(empty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) {
            unset($data[self::FILE_LIFE_KEY]); 
     		return $data;			
     	}
     	return false;
    }    
    
    /**
     * 写入缓存文件
     *
     * @param  string $file   缓存路径
     * @param  string $string 缓存信息
     * @return boolean true 成功
     */
    protected function _filePutContents($file, $string)
    {
    	$self = & self::getInstance();
        $result = false;
        $f = @fopen($file, &#39;ab+&#39;);
        if ($f) {
            if ($self->_options[&#39;file_locking&#39;]) @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $string);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
        @chmod($file, $self->_options[&#39;cache_file_umask&#39;]);
        return $result;
    }
    
    /**
     * 格式化后的缓存文件路径
     *
     * @param  string $id 缓存id
     * @return string 缓存文件名(包括路径)
     */
    protected function _file($id)
    {
    	$self = & self::getInstance();
        $fileName = $self->_idToFileName($id);
        return $self->_options[&#39;cache_dir&#39;] . $fileName;
    }    
    
    /**
     * 格式化后的缓存文件名字
     *
     * @param  string $id 缓存id
     * @return string 缓存文件名
     */
    protected function _idToFileName($id)
    {
    	$self = & self::getInstance();
        $self->_id = $id;
        $prefix = $self->_options[&#39;file_name_prefix&#39;];
        $result = $prefix . &#39;---&#39; . $id;
        return $result;
    }   
    
    /**
     * 判断缓存是否存在
     *
     * @param  string $id Cache id
     * @return boolean True 缓存存在 False 缓存不存在
     */
    static function test($id)
    {
    	$self = & self::getInstance();
        $file = $self->_file($id);
        
        if (!is_file($file)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 得到缓存信息
     *
     * @param  string $file 缓存路径
     * @return string 缓存内容
     */
    protected function _fileGetContents($file)
    {
        if (!is_file($file)) {
            return false;
        }
        return include $file;
    }     
    
    /**
     * 清除所有缓存
     * 
     * @return void
     */    
    static function clear()
    {
    	$self = & self::getInstance();
    	$self->save(&#39;CLEAR_ALL&#39;,self::CLEAR_ALL_KEY);	
    }   
	
    /**
     * 清除一条缓存
     * 
     * @param string cache id	 
     * @return void
     */   
    static function del($id)
    {
		$self = & self::getInstance();
    	if(!$self->test($id)){
    		// 该缓存不存在
    		return false;
    	}
    	$file = $self->_file($id);
    	return unlink($file);
    }	
}
登录后复制

3. [代码]存入数据

<?php
$config = array(
	&#39;name&#39; => &#39;xiaojiong&#39;,
	&#39;qq&#39;   => &#39;290747680&#39;,
	&#39;age&#39;  => &#39;20&#39;,
);

//第一个参数 缓存data
//第二个参数 缓存id
//第三个参数 cache_life 0 永不过期(cache::clear()清空所有除外) 默认cache_life 为option_cache_life
cache::save($config,&#39;config&#39;,0);
登录后复制

4. [代码]载入数据

<?php
//只有一个参数 cache_id
$config = cache::load(&#39;config&#39;);
登录后复制

5. [代码]清空缓存

<?php
//清空指定缓存
cache::del(&#39;config&#39;);
//清空所有缓存
cache::clear();
登录后复制

6. [代码]cache信息配置

//在执行所有cache_func前调用

$_options = array(
    &#39;cache_dir&#39; => &#39;./cache&#39;, //缓存文件目录
    &#39;file_name_prefix&#39; => &#39;cache&#39;,//缓存文件前缀
    &#39;file_life&#39;  => 100000, //缓存文件生命
);
cache::setOptions($options);

//再执行 就会按着新配置信息执行,否则是默认信息
cache::save($arr,&#39;arr&#39;);


//就是这个方法 貌似不合理 望大家指点
登录后复制

以上就是php 文件缓存的内容,更多相关内容请关注PHP中文网(www.php.cn)!


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 Dec 24, 2024 pm 04:42 PM

PHP 8.4 带来了多项新功能、安全性改进和性能改进,同时弃用和删除了大量功能。 本指南介绍了如何在 Ubuntu、Debian 或其衍生版本上安装 PHP 8.4 或升级到 PHP 8.4

我后悔之前不知道的 7 个 PHP 函数 我后悔之前不知道的 7 个 PHP 函数 Nov 13, 2024 am 09:42 AM

如果您是一位经验丰富的 PHP 开发人员,您可能会感觉您已经在那里并且已经完成了。您已经开发了大量的应用程序,调试了数百万行代码,并调整了一堆脚本来实现操作

如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 Dec 20, 2024 am 11:31 AM

Visual Studio Code,也称为 VS Code,是一个免费的源代码编辑器 - 或集成开发环境 (IDE) - 可用于所有主要操作系统。 VS Code 拥有针对多种编程语言的大量扩展,可以轻松编写

在PHP API中说明JSON Web令牌(JWT)及其用例。 在PHP API中说明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息,主要用于身份验证和信息交换。1.JWT由Header、Payload和Signature三部分组成。2.JWT的工作原理包括生成JWT、验证JWT和解析Payload三个步骤。3.在PHP中使用JWT进行身份验证时,可以生成和验证JWT,并在高级用法中包含用户角色和权限信息。4.常见错误包括签名验证失败、令牌过期和Payload过大,调试技巧包括使用调试工具和日志记录。5.性能优化和最佳实践包括使用合适的签名算法、合理设置有效期、

您如何在PHP中解析和处理HTML/XML? 您如何在PHP中解析和处理HTML/XML? Feb 07, 2025 am 11:57 AM

本教程演示了如何使用PHP有效地处理XML文档。 XML(可扩展的标记语言)是一种用于人类可读性和机器解析的多功能文本标记语言。它通常用于数据存储

php程序在字符串中计数元音 php程序在字符串中计数元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符组成的序列,包括字母、数字和符号。本教程将学习如何使用不同的方法在PHP中计算给定字符串中元音的数量。英语中的元音是a、e、i、o、u,它们可以是大写或小写。 什么是元音? 元音是代表特定语音的字母字符。英语中共有五个元音,包括大写和小写: a, e, i, o, u 示例 1 输入:字符串 = "Tutorialspoint" 输出:6 解释 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。总共有 6 个元

解释PHP中的晚期静态绑定(静态::)。 解释PHP中的晚期静态绑定(静态::)。 Apr 03, 2025 am 12:04 AM

静态绑定(static::)在PHP中实现晚期静态绑定(LSB),允许在静态上下文中引用调用类而非定义类。1)解析过程在运行时进行,2)在继承关系中向上查找调用类,3)可能带来性能开销。

什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? 什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些?PHP的魔法方法包括:1.\_\_construct,用于初始化对象;2.\_\_destruct,用于清理资源;3.\_\_call,处理不存在的方法调用;4.\_\_get,实现动态属性访问;5.\_\_set,实现动态属性设置。这些方法在特定情况下自动调用,提升代码的灵活性和效率。

See all articles