백엔드 개발 PHP 튜토리얼 PHP 缓存实现代码及详细注释_php技巧

PHP 缓存实现代码及详细注释_php技巧

May 17, 2016 am 09:25 AM
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 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 {

protected $_cachesDir = 'cache';

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

/**
* 获取缓存文件
*
* @param string $key
* @return string
*/
protected function _getCacheFile($key) {
return $this->_cachesDir . '/' . substr($key, 0, 2) . '/' . $key . '.php';
}
/**
* 读取缓存变量
* 为防止信息泄露,缓存文件格式为php文件,并以""开头
*
* @param string $key 缓存下标
* @return mixed
*/
public function fetch($key) {
$cacheFile = self::_getCacheFile($key);
if (file_exists($cacheFile) && is_readable($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" target="_blank">!@mkdir($cacheDir, 0755, true)) {
throw new CacheException("Could not make cache directory");
}
}
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($cacheFile" target="_blank">!@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" target="_blank">!@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;
}
}
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

CakePHP 프로젝트 구성 CakePHP 프로젝트 구성 Sep 10, 2024 pm 05:25 PM

이번 장에서는 CakePHP의 환경 변수, 일반 구성, 데이터베이스 구성, 이메일 구성에 대해 알아봅니다.

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로 업그레이드하는 방법을 설명합니다.

CakePHP 날짜 및 시간 CakePHP 날짜 및 시간 Sep 10, 2024 pm 05:27 PM

cakephp4에서 날짜와 시간을 다루기 위해 사용 가능한 FrozenTime 클래스를 활용하겠습니다.

CakePHP 파일 업로드 CakePHP 파일 업로드 Sep 10, 2024 pm 05:27 PM

파일 업로드 작업을 위해 양식 도우미를 사용할 것입니다. 다음은 파일 업로드의 예입니다.

CakePHP 라우팅 CakePHP 라우팅 Sep 10, 2024 pm 05:25 PM

이번 장에서는 라우팅과 관련된 다음과 같은 주제를 학습하겠습니다.

CakePHP 토론 CakePHP 토론 Sep 10, 2024 pm 05:28 PM

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

CakePHP 유효성 검사기 만들기 CakePHP 유효성 검사기 만들기 Sep 10, 2024 pm 05:26 PM

컨트롤러에 다음 두 줄을 추가하면 유효성 검사기를 만들 수 있습니다.

See all articles