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);
相关推荐
bksczm2 分钟前
linux之线程概念和控制
linux·开发语言·c++
SamDeepThinking4 分钟前
Vibe Coding最重要的是Spec
后端·程序员·ai编程
掘金_答案7 分钟前
上线那天,一个 ConcurrentHashMap 差点送走我的 AI 客服——3 天排查 JVM 血泪史
java·后端·架构
妙码生花12 分钟前
从 PHP 到 AI + Golang,程序员自救转型手记(三十三):权限规则管理器
后端·go·gin
JackieZhengChina34 分钟前
零依赖轻量级JS悬浮提示插件title2tip-js的使用教程
开发语言·javascript·ecmascript
Kim_wang42 分钟前
agent项目部署流程
人工智能·后端
鸽子一号1 小时前
c#之信号量Semaphore
笔记
kdxiaojie1 小时前
Linux 驱动研究 —— I2C (5)
linux·运维·笔记·学习
程序员天天困1 小时前
优雅记录操作日志:从注解到 SpEL 的全链路实践与开源方案对比
java·后端
李永奉2 小时前
杰理可视化SDK开发-【BUG】配置“TWS两边同时按消息使能”功能后,按键单击功能无效失灵
开发语言·单片机·嵌入式硬件·物联网·bug