0

0

php支持apc和文件缓存的类

PHP中文网

PHP中文网

发布时间:2016-05-23 16:36:48

|

1240人浏览过

|

来源于php中文网

原创

1. [代码][PHP]代码   

 isLocked($key)) {
			return $this;
		}

		$tries = 10;
		$count = 0;
		do {
			usleep(200);
			$count++;
		} while ($count <= $tries && $this->isLocked($key));// 最多做十次睡眠等待解锁,超时则跳过并解锁

		$this -> isLocked($key) && $this -> unlock($key);

		return $this;
	}

}

/**
 * APC扩展缓存实现
 *
 *
 * @category   Mjie
 * @package    Cache
 * @author     流水孟春
 * @copyright  Copyright (c) 2008- 
 * @license    New BSD License
 * @version    $Id: Cache/Apc.php 版本号 2010-04-18 23:02 cmpan $
 */
class Cache_Apc extends Cache_Abstract {

	protected $_prefix = 'cache.mjie.net';

	public function __construct() {
		if (!function_exists('apc_cache_info')) {
			throw new CacheException('apc extension didn't installed');
		}
	}

	/**
	 * 保存缓存变量
	 *
	 * @param string $key
	 * @param mixed $value
	 * @return bool
	 */
	public function store($key, $value) {
		return apc_store($this -> _storageKey($key), $value);
	}

	/**
	 * 读取缓存
	 *
	 * @param string $key
	 * @return mixed
	 */
	public function fetch($key) {
		return apc_fetch($this -> _storageKey($key));
	}

	/**
	 * 清除缓存
	 *
	 * @return Cache_Apc
	 */
	public function clear() {
		apc_clear_cache();
		return $this;
	}

	/**
	 * 删除缓存单元
	 *
	 * @return Cache_Apc
	 */
	public function delete($key) {
		apc_delete($this -> _storageKey($key));
		return $this;
	}

	/**
	 * 缓存单元是否被锁定
	 *
	 * @param string $key
	 * @return bool
	 */
	public function isLocked($key) {
		if ((apc_fetch($this -> _storageKey($key) . '.lock')) === false) {
			return false;
		}

		return true;
	}

	/**
	 * 锁定缓存单元
	 *
	 * @param string $key
	 * @return Cache_Apc
	 */
	public function lock($key) {
		apc_store($this -> _storageKey($key) . '.lock', '', 5);
		return $this;
	}

	/**
	 * 缓存单元解锁
	 *
	 * @param string $key
	 * @return Cache_Apc
	 */
	public function unlock($key) {
		apc_delete($this -> _storageKey($key) . '.lock');
		return $this;
	}

	/**
	 * 完整缓存名
	 *
	 * @param string $key
	 * @return string
	 */
	private function _storageKey($key) {
		return $this -> _prefix . '_' . $key;
	}

}

/**
 * 文件缓存实现
 *
 *
 * @category   Mjie
 * @package    Cache
 * @author     流水孟春
 * @copyright  Copyright (c) 2008- 
 * @license    New BSD License
 * @version    $Id: Cache/File.php 版本号 2010-04-18 16:46 cmpan $
 */
class Cache_File extends Cache_Abstract {
	public $useSubdir = false;

	protected $_cachesDir = 'cache';

	public function __construct() {
		if (defined('DATA_DIR')) {
			$this -> _setCacheDir(DATA_DIR . '/cache');
		}
	}

	/**
	 * 获取缓存文件
	 *
	 * @param string $key
	 * @return string
	 */
	protected function _getCacheFile($key) {
		$subdir = $this -> useSubdir ? substr($key, 0, 2) . '/' : '';
		return $this -> _cachesDir . '/' . $subdir . $key . '.php';
	}

	/**
	 * 读取缓存变量
	 * 为防止信息泄露,缓存文件格式为php文件,并以""开头
	 *
	 * @param string $key 缓存下标
	 * @return mixed
	 */
	public function fetch($key) {
		$cacheFile = self::_getCacheFile($key);
		if (file_exists($cacheFile) && is_readable($cacheFile)) {
			// include 方式
			//return include $cacheFile;
			// 系列化方式

			return unserialize(@file_get_contents($cacheFile, false, NULL, 13));
		}

		return false;
	}

	/**
	 * 缓存变量
	 * 为防止信息泄露,缓存文件格式为php文件,并以""开头
	 *
	 * @param string $key 缓存变量下标
	 * @param string $value 缓存变量的值
	 * @return bool
	 */
	public function store($key, $value) {
		$cacheFile = self::_getCacheFile($key);
		$cacheDir = dirname($cacheFile);

		if (!is_dir($cacheDir)) {
			if (!@mkdir($cacheDir, 0755, true)) {
				throw new CacheException("Could not make cache directory");
			}
		}
		// 用include方式
		//return @file_put_contents($cacheFile, '' . serialize($value));
	}

	/**
	 * 删除缓存变量
	 *
	 * @param string $key 缓存下标
	 * @return Cache_File
	 */
	public function delete($key) {
		if (emptyempty($key)) {
			throw new CacheException("Missing argument 1 for Cache_File::delete()");
		}

		$cacheFile = self::_getCacheFile($key);
		if (!@unlink($cacheFile)) {
			throw new CacheException("Cache file could not be deleted");
		}

		return $this;
	}

	/**
	 * 缓存单元是否已经锁定
	 *
	 * @param string $key
	 * @return bool
	 */
	public function isLocked($key) {
		$cacheFile = self::_getCacheFile($key);
		clearstatcache();
		return file_exists($cacheFile . '.lock');
	}

	/**
	 * 锁定
	 *
	 * @param string $key
	 * @return Cache_File
	 */
	public function lock($key) {
		$cacheFile = self::_getCacheFile($key);
		$cacheDir = dirname($cacheFile);
		if (!is_dir($cacheDir)) {
			if (!@mkdir($cacheDir, 0755, true)) {
				if (!is_dir($cacheDir)) {
					throw new CacheException("Could not make cache directory");
				}
			}
		}

		// 设定缓存锁文件的访问和修改时间
		@touch($cacheFile . '.lock');
		return $this;
	}

	/**
	 * 解锁
	 *
	 * @param string $key
	 * @return Cache_File
	 */
	public function unlock($key) {
		$cacheFile = self::_getCacheFile($key);
		@unlink($cacheFile . '.lock');
		return $this;
	}

	/**
	 * 设置文件缓存目录
	 * @param string $dir
	 * @return Cache_File
	 */
	protected function _setCacheDir($dir) {
		$this -> _cachesDir = rtrim(str_replace('\', '/', trim($dir)), '/');
		clearstatcache();
		if (!is_dir($this -> _cachesDir)) {
			mkdir($this -> _cachesDir, 0755, true);
		}
		//
		return $this;
	}

	/**
	 * 清空所有缓存
	 *
	 * @return Cache_File
	 */
	public function clear() {
		// 遍历目录清除缓存
		$cacheDir = $this -> _cachesDir;
		$d = dir($cacheDir);
		while (false !== ($entry = $d -> read())) {
			if ('.' == $entry[0]) {
				continue;
			}

			$cacheEntry = $cacheDir . '/' . $entry;
			if (is_file($cacheEntry)) {
				@unlink($cacheEntry);
			} elseif (is_dir($cacheEntry)) {
				// 缓存文件夹有两级
				$d2 = dir($cacheEntry);
				while (false !== ($entry = $d2 -> read())) {
					if ('.' == $entry[0]) {
						continue;
					}

					$cacheEntry .= '/' . $entry;
					if (is_file($cacheEntry)) {
						@unlink($cacheEntry);
					}
				}
				$d2 -> close();
			}
		}
		$d -> close();

		return $this;
	}

}

/**
 * 缓存单元的数据结构
 * array(
 *         'time' => time(),     // 缓存写入时的时间戳
 *         'expire' => $expire, // 缓存过期时间
 *         'valid' => true,         // 缓存是否有效
 *         'data' => $value         // 缓存的值
 * );
 */
final class Cache {
	/**
	 * 缓存过期时间长度(s)
	 *
	 * @var int
	 */
	private $_expire = 3600;
	/**
	 * 缓存处理类
	 *
	 * @var Cache_Abstract
	 */
	private $_storage = null;
	/**
	 * @return Cache
	 */
	static public function createCache($cacheClass = 'Cache_File') {
		return new self($cacheClass);
	}

	private function __construct($cacheClass) {
		$this -> _storage = new $cacheClass();
	}

	/**
	 * 设置缓存
	 *
	 * @param string $key
	 * @param mixed $value
	 * @param int $expire
	 */
	public function set($key, $value, $expire = false) {
		if (!$expire) {
			$expire = $this -> _expire;
		}

		$this -> _storage -> checkLock($key);

		$data = array('time' => time(), 'expire' => $expire, 'valid' => true, 'data' => $value);
		$this -> _storage -> lock($key);

		try {
			$this -> _storage -> store($key, $data);
			$this -> _storage -> unlock($key);
		} catch (CacheException $e) {
			$this -> _storage -> unlock($key);
			throw $e;
		}
	}

	/**
	 * 读取缓存
	 *
	 * @param string $key
	 * @return mixed
	 */
	public function get($key) {
		$data = $this -> fetch($key);
		if ($data && $data['valid'] && !$data['isExpired']) {
			return $data['data'];
		}

		return false;
	}

	/**
	 * 读缓存,包括过期的和无效的,取得完整的存贮结构
	 *
	 * @param string $key
	 */
	public function fetch($key) {
		$this -> _storage -> checkLock($key);
		$data = $this -> _storage -> fetch($key);
		if ($data) {
			$data['isExpired'] = (time() - $data['time']) > $data['expire'] ? true : false;
			return $data;
		}

		return false;
	}

	/**
	 * 删除缓存
	 *
	 * @param string $key
	 */
	public function delete($key) {
		$this -> _storage -> checkLock($key) -> lock($key) -> delete($key) -> unlock($key);
	}

	public function clear() {
		$this -> _storage -> clear();
	}

	/**
	 * 把缓存设为无效
	 *
	 * @param string $key
	 */
	public function setInvalidate($key) {
		$this -> _storage -> checkLock($key) -> lock($key);
		try {
			$data = $this -> _storage -> fetch($key);
			if ($data) {
				$data['valid'] = false;
				$this -> _storage -> store($key, $data);
			}
			$this -> _storage -> unlock($key);
		} catch (CacheException $e) {
			$this -> _storage -> unlock($key);
			throw $e;
		}
	}

	/**
	 * 设置缓存过期时间(s)
	 *
	 * @param int $expire
	 */
	public function setExpire($expire) {
		$this -> _expire = (int)$expire;
		return $this;
	}

}

                   

佰思超强智能分类信息系统
佰思超强智能分类信息系统

全面支持web 2.0的智能分类信息系统 支持多种分类 支持无限分类 支持每个分类下有任意文章 分类下可以有分类和文章同时存在 文章可以属于任何分类 等等功能,智能的,百变分类信息系统 默认管理员: admin 默认密码: 123

下载

                   

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

php

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

相关专题

更多
高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

43

2026.01.16

全民K歌得高分教程大全
全民K歌得高分教程大全

本专题整合了全民K歌得高分技巧汇总,阅读专题下面的文章了解更多详细内容。

84

2026.01.16

C++ 单元测试与代码质量保障
C++ 单元测试与代码质量保障

本专题系统讲解 C++ 在单元测试与代码质量保障方面的实战方法,包括测试驱动开发理念、Google Test/Google Mock 的使用、测试用例设计、边界条件验证、持续集成中的自动化测试流程,以及常见代码质量问题的发现与修复。通过工程化示例,帮助开发者建立 可测试、可维护、高质量的 C++ 项目体系。

24

2026.01.16

java数据库连接教程大全
java数据库连接教程大全

本专题整合了java数据库连接相关教程,阅读专题下面的文章了解更多详细内容。

35

2026.01.15

Java音频处理教程汇总
Java音频处理教程汇总

本专题整合了java音频处理教程大全,阅读专题下面的文章了解更多详细内容。

16

2026.01.15

windows查看wifi密码教程大全
windows查看wifi密码教程大全

本专题整合了windows查看wifi密码教程大全,阅读专题下面的文章了解更多详细内容。

56

2026.01.15

浏览器缓存清理方法汇总
浏览器缓存清理方法汇总

本专题整合了浏览器缓存清理教程汇总,阅读专题下面的文章了解更多详细内容。

16

2026.01.15

ps图片相关教程汇总
ps图片相关教程汇总

本专题整合了ps图片设置相关教程合集,阅读专题下面的文章了解更多详细内容。

9

2026.01.15

ppt一键生成相关合集
ppt一键生成相关合集

本专题整合了ppt一键生成相关教程汇总,阅读专题下面的的文章了解更多详细内容。

26

2026.01.15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PHP课程
PHP课程

共137课时 | 8.7万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 7.3万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号