PHP自定义文件缓存实现

文件缓存:可以将PHP脚本的执行结果缓存到文件中。当一个PHP脚本被请求时,先查看是否存在缓存文件,如果存在且未过期,则直接读取缓存文件内容返回给客户端,而无需执行脚本

1、文件缓存写法一,每个文件缓存一个数据,缺点文件可能太多

php 复制代码
function getFileCache($key, $value = null, $expiry = 3600) {
    $cacheDir = "D:\\phpstudy_pro\\WWW\\cache\\";
    $cacheFile = $cacheDir . md5($key) . '.txt';

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $expiry)) {
        return file_get_contents($cacheFile);
    }

    if ($value !== null) {
        // 将$value参数的值保存到缓存文件中
        file_put_contents($cacheFile, $value);
        return $value;
    }

    // 保存数据到缓存文件中
    file_put_contents($cacheFile, $value);

    return $value;
}

// 缓存具体的值
$cacheValue = 'example_value';
 getFileCache('example_key', $cacheValue);

// 使用示例
$data = getFileCache('example_key');
echo $data;

2、文件缓存写法二,一个文件缓存所有数据,缺点可能文件太大读写变慢

php 复制代码
function getFileCache($key, $value = null, $expiry = 3600) {
    $cacheDir = "D:\\phpstudy_pro\\WWW\\cache\\";
    $cacheFile = $cacheDir .  'cache.txt';
    $file=false;
    if(file_exists($cacheFile)){
        $file= file_get_contents($cacheFile);
    }
    if($file){
         $data=unserialize($file);
    }else{
        $data=[];
    }
    if($value){
        $data[$key]=["data"=>$value,'expiry'=>time()+$expiry];

        file_put_contents($cacheFile, serialize($data));
        return true;
    }else{
        if(isset($data[$key])&&$data[$key]['expiry']>time()){

             return  $data[$key]['data'];
        }
        return null;
    }
}
// 缓存具体的值
$cacheValue = 'example_value';
getFileCache('example_key', $cacheValue);
$cacheValue = 'example_value2';
getFileCache('example_key2', $cacheValue);
// 使用示例
$data = getFileCache('example_key');
var_dump($data);
$data2 = getFileCache('example_key2');
var_dump($data2);
相关推荐
ai小鬼头27 分钟前
百度秒搭发布:无代码编程如何让普通人轻松打造AI应用?
前端·后端·github
考虑考虑28 分钟前
@FilterRegistration和@ServletRegistration注解
spring boot·后端·spring
一只叫煤球的猫31 分钟前
🔥 同事混用@Transactional和TransactionTemplate被我怼了,三种事务管理到底怎么选?
java·spring boot·后端
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
学Linux的语莫9 天前
python基础语法
开发语言·python
你的人类朋友9 天前
(●'◡'●)从Dockerfile快速入门Docker Compose
后端
暖馒9 天前
C#委托与事件的区别
开发语言·c#
GetcharZp9 天前
「神器推荐」Rclone:轻松玩转云端存储,FTP 也能飞起来!
后端
华子w9089258599 天前
基于 SpringBoot+JSP 的医疗预约与诊断系统设计与实现
java·spring boot·后端