首頁 php教程 PHP源码 php支持apc和文件缓存的类

php支持apc和文件缓存的类

May 23, 2016 pm 04:36 PM
php

1. [代码][PHP]代码   

<?php
class CacheException extends Exception {
}
/**
 * 缓存抽象类
 */
abstract class Cache_Abstract {
	/**
	 * 读缓存变量
	 *
	 * @param string $key 缓存下标
	 * @return mixed
	 */
	abstract public function fetch($key);

	/**
	 * 缓存变量
	 *
	 * @param string $key 缓存变量下标
	 * @param string $value 缓存变量的值
	 * @return bool
	 */
	abstract public function store($key, $value);

	/**
	 * 删除缓存变量
	 *
	 * @param string $key 缓存下标
	 * @return Cache_Abstract
	 */
	abstract public function delete($key);

	/**
	 * 清(删)除所有缓存
	 *
	 * @return Cache_Abstract
	 */
	abstract public function clear();

	/**
	 * 锁定缓存变量
	 *
	 * @param string $key 缓存下标
	 * @return Cache_Abstract
	 */
	abstract public function lock($key);

	/**
	 * 缓存变量解锁
	 *
	 * @param string $key 缓存下标
	 * @return Cache_Abstract
	 */
	abstract public function unlock($key);

	/**
	 * 取得缓存变量是否被锁定
	 *
	 * @param string $key 缓存下标
	 * @return bool
	 */
	abstract public function isLocked($key);

	/**
	 * 确保不是锁定状态
	 * 最多做$tries次睡眠等待解锁,超时则跳过并解锁
	 *
	 * @param string $key 缓存下标
	 */
	public function checkLock($key) {
		if (!$this -> 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- <cmpan(at)qq.com>
 * @license    New BSD License
 * @version    $Id: Cache/Apc.php 版本号 2010-04-18 23:02 cmpan $
 */
class Cache_Apc extends Cache_Abstract {

	protected $_prefix = &#39;cache.mjie.net&#39;;

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

	/**
	 * 保存缓存变量
	 *
	 * @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) . &#39;.lock&#39;)) === false) {
			return false;
		}

		return true;
	}

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

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

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

}

/**
 * 文件缓存实现
 *
 *
 * @category   Mjie
 * @package    Cache
 * @author     流水孟春
 * @copyright  Copyright (c) 2008- <cmpan(at)qq.com>
 * @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 = &#39;cache&#39;;

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

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

	/**
	 * 读取缓存变量
	 * 为防止信息泄露,缓存文件格式为php文件,并以"<?php exit;?>"开头
	 *
	 * @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文件,并以"<?php exit;?>"开头
	 *
	 * @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, &#39;<?php return &#39; . var_export($value, true). &#39;;&#39;);

		return @file_put_contents($cacheFile, &#39;<?php exit;?>&#39; . 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 . &#39;.lock&#39;);
	}

	/**
	 * 锁定
	 *
	 * @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 . &#39;.lock&#39;);
		return $this;
	}

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

	/**
	 * 设置文件缓存目录
	 * @param string $dir
	 * @return Cache_File
	 */
	protected function _setCacheDir($dir) {
		$this -> _cachesDir = rtrim(str_replace(&#39;\&#39;, &#39;/&#39;, trim($dir)), &#39;/&#39;);
		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 (&#39;.&#39; == $entry[0]) {
				continue;
			}

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

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

		return $this;
	}

}

/**
 * 缓存单元的数据结构
 * array(
 *         &#39;time&#39; => time(),     // 缓存写入时的时间戳
 *         &#39;expire&#39; => $expire, // 缓存过期时间
 *         &#39;valid&#39; => true,         // 缓存是否有效
 *         &#39;data&#39; => $value         // 缓存的值
 * );
 */
final class Cache {
	/**
	 * 缓存过期时间长度(s)
	 *
	 * @var int
	 */
	private $_expire = 3600;
	/**
	 * 缓存处理类
	 *
	 * @var Cache_Abstract
	 */
	private $_storage = null;
	/**
	 * @return Cache
	 */
	static public function createCache($cacheClass = &#39;Cache_File&#39;) {
		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(&#39;time&#39; => time(), &#39;expire&#39; => $expire, &#39;valid&#39; => true, &#39;data&#39; => $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[&#39;valid&#39;] && !$data[&#39;isExpired&#39;]) {
			return $data[&#39;data&#39;];
		}

		return false;
	}

	/**
	 * 读缓存,包括过期的和无效的,取得完整的存贮结构
	 *
	 * @param string $key
	 */
	public function fetch($key) {
		$this -> _storage -> checkLock($key);
		$data = $this -> _storage -> fetch($key);
		if ($data) {
			$data[&#39;isExpired&#39;] = (time() - $data[&#39;time&#39;]) > $data[&#39;expire&#39;] ? 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[&#39;valid&#39;] = 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;
	}

}
登入後複製

                   

                   

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1318
25
PHP教程
1269
29
C# 教程
1248
24
在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程序在字符串中計數元音 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,實現動態屬性設置。這些方法在特定情況下自動調用,提升代碼的靈活性和效率。

PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

See all articles