php文件缓存类汇总
这篇文章主要介绍了php文件缓存类,实例汇总了常见的文件缓存类及其用法,非常具有实用价值,需要的朋友可以参考下
本文实例讲述了php的文件缓存类。分享给大家供大家参考。具体分析如下:
缓存类是我们开发应用中会常用使用到的功能,下面就来给大家整理几个php文件缓存类了,,各个文件缓存类写法不同,但在性能上会有区别,有兴趣测试的朋友可测试一下这些缓存类。
例1
复制代码 代码如下:
$fzz = new fzz_cache;
$fzz->kk = $_SERVER; //写入缓存
//$fzz->set("kk",$_SERVER,10000); //此方法不与类属性想冲突,可以用任意缓存名;
print_r($fzz->kk); //读取缓存
//print_r($fzz->get("kk"));
//unset($fzz->kk); //删除缓存
//$fzz->_unset("kk");
var_dump(isset($fzz->kk)); //判断缓存是否存在
//$fzz->_isset("kk");
//$fzz->clear(); //清理过期缓存
//$fzz->clear_all(); //清理所有缓存文件
class fzz_cache{
public $limit_time = 20000; //缓存过期时间
public $cache_dir = "data"; //缓存文件保存目录
//写入缓存
function __set($key , $val){
$this->_set($key ,$val);
}
//第三个参数为过期时间
function _set($key ,$val,$limit_time=null){
$limit_time = $limit_time ? $limit_time : $this->limit_time;
$file = $this->cache_dir."/".$key.".cache";
$val = serialize($val);
@file_put_contents($file,$val) or $this->error(__line__,"fail to write in file");
@chmod($file,0777);
@touch($file,time()+$limit_time) or $this->error(__line__,"fail to change time");
}
//读取缓存
function __get($key){
return $this->_get($key);
}
function _get($key){
$file = $this->cache_dir."/".$key.".cache";
if (@filemtime($file)>=time()){
return unserialize(file_get_contents($file));
}else{
@unlink($file) or $this->error(__line__,"fail to unlink");
return false;
}
}
//删除缓存文件
function __unset($key){
return $this->_unset($key);
}
function _unset($key){
if (@unlink($this->cache_dir."/".$key.".cache")){
return true;
}else{
return false;
}
}
//检查缓存是否存在,过期则认为不存在
function __isset($key){
return $this->_isset($key);
}
function _isset($key){
$file = $this->cache_dir."/".$key.".cache";
if (@filemtime($file)>=time()){
return true;
}else{
@unlink($file) ;
return false;
}
}
//清除过期缓存文件
function clear(){
$files = scandir($this->cache_dir);
foreach ($files as $val){
if (filemtime($this->cache_dir."/".$val)
@unlink($this->cache_dir."/".$val);
}
}
}
//清除所有缓存文件
function clear_all(){
$files = scandir($this->cache_dir);
foreach ($files as $val){
@unlink($this->cache_dir."/".$val);
}
}
function error($msg,$debug = false) {
$err = new Exception($msg);
$str = "
<br> <span>error:</span><br> ".print_r($err->getTrace(),1)."<br>
if($debug == true) {
file_put_contents(date('Y-m-d H_i_s').".log",$str);
return $str;
}else{
die($str);
}
}
}
?>
例2.从CI社区的stblog和CI的file_helper类中提取出来的php文件缓存类,一个简单的基于文件的key->value缓存类。
这个类可以用来缓存一些基本信息,比如博客的header,footer,sidebar中的一些不经常变化,从数据库中取出的内容,取数据前先判断文件缓存中的内容是否过期,如果没过期取出来,过期了则连接数据库查询,并将结果重新写入文件缓存,更新过期时间。跟memcache使用类似,不过更方便。用在一些小的应用上足够了.
具体代码如下
复制代码 代码如下:
define('DIRECTORY_SEPARATOR','/');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE','wb');
define('FOPEN_WRITE_CREATE','ab');
define('DIR_WRITE_MODE', 0777);
class FileCache {
/**
* 缓存路径
*
* @access private
* @var string
*/
private $_cache_path;
/**
* 缓存过期时间,单位是秒second
*
* @access private
* @var int
*/
private $_cache_expire;
/**
* 解析函数,设置缓存过期实践和存储路径
*
* @access public
* @return void
*/
public function __construct($expire, $cache_path)
{
$this->_cache_expire = $expire;
$this->_cache_path = $cache_path;
}
/**
* 缓存文件名
*
* @access public
* @param string $key
* @return void
*/
private function _file($key)
{
return $this->_cache_path . md5($key);
}
/**
* 设置缓存
*
* @access public
* @param string $key 缓存的唯一键
* @param string $data 缓存的内容
* @return bool
*/
public function set($key, $data)
{
$value = serialize($data);
$file = $this->_file($key);
return $this->write_file($file, $value);
}
/**
* 获取缓存
*
* @access public
* @param string $key 缓存的唯一键
* @return mixed
*/
public function get($key)
{
$file = $this->_file($key);
/** 文件不存在或目录不可写 */
if (!file_exists($file) || !$this->is_really_writable($file))
{
return false;
}
/** 缓存没有过期,仍然可用 */
if ( time() _cache_expire) )
{
$data = $this->read_file($file);
if(FALSE !== $data)
{
return unserialize($data);
}
return FALSE;
}
/** 缓存过期,删除之 */
@unlink($file);
return FALSE;
}
function read_file($file)
{
if ( ! file_exists($file))
{
return FALSE;
}
if (function_exists('file_get_contents'))
{
return file_get_contents($file);
}
if ( ! $fp = @fopen($file, FOPEN_READ))
{
return FALSE;
}
flock($fp, LOCK_SH);//读取之前加上共享锁
$data = '';
if (filesize($file) > 0)
{
$data =& fread($fp, filesize($file));
}
flock($fp, LOCK_UN);//释放锁
fclose($fp);
return $data;
}
function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE)
{
if ( ! $fp = @fopen($path, $mode))
{
return FALSE;
}
flock($fp, LOCK_EX);
fwrite($fp, $data);
flock($fp, LOCK_UN);
fclose($fp);
return TRUE;
}
function is_really_writable($file)//兼容各平台判断文件是否有写入权限
{
// If we're on a Unix server with safe_mode off we call is_writable
if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
{
return is_writable($file);
}
// For windows servers and safe_mode "on" installations we'll actually
// write a file then read it. Bah...
if (is_dir($file))
{
$file = rtrim($file, '/').'/'.md5(rand(1,100));
if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
{
return FALSE;
}
fclose($fp);
@chmod($file, DIR_WRITE_MODE);
@unlink($file);
return TRUE;
}
elseif (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
{
return FALSE;
}
fclose($fp);
return TRUE;
}
}
$cache = new FileCache(30,'cache/');
$cache->set('test','this is a test.');
print $cache->get('test');
/* End of file FlieCache.php */
例3.自己觉得很好用的php文件缓存
复制代码 代码如下:

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

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

뜨거운 주제











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

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

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

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