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);
相关推荐
王码码203514 小时前
Go语言的测试:从单元测试到集成测试
后端·golang·go·接口
王码码203514 小时前
Go语言中的测试:从单元测试到集成测试
后端·golang·go·接口
以神为界14 小时前
Python入门实操:基础语法+爬虫入门+模块使用全指南
开发语言·网络·爬虫·python·安全·web
嵌入式×边缘AI:打怪升级日志15 小时前
使用JsonRPC实现前后台
前端·后端
逻辑驱动的ken15 小时前
Java高频面试题:03
java·开发语言·面试·求职招聘·春招
北漂Zachary15 小时前
Laravel 8.x 核心特性全解析
php·laravel
噜噜大王_15 小时前
深入理解 C 语言内存操作函数:memcpy、memmove、memset、memcmp
c语言·开发语言
北漂Zachary15 小时前
Laravel 5.x升级亮点:从架构优化到API革新
架构·php·laravel
广师大-Wzx15 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
野生技术架构师15 小时前
Java NIO到底是个什么东西?
java·开发语言·nio