首页 > php框架 > Laravel > 正文

Laravel自定义缓存驱动?缓存扩展如何实现?

月夜之吻
发布: 2025-09-26 09:04:02
原创
797人浏览过
首先创建实现Store接口的自定义缓存类,然后通过服务提供者用Cache::extend注册驱动,最后在config/cache.php中配置使用该驱动。

laravel自定义缓存驱动?缓存扩展如何实现?

在Laravel中实现自定义缓存驱动,核心在于利用其强大的缓存管理器(Cache Manager)的扩展能力。这通常涉及编写一个服务提供者,并在其中注册一个新的缓存驱动器,该驱动器需要实现Illuminate\Contracts\Cache\Store接口,从而让Laravel知道如何与你的自定义缓存后端进行交互。说白了,就是告诉Laravel:“嘿,除了你认识的Redis、Memcached,我这儿还有个新的缓存地方,你按我说的去存取就行。”

解决方案

要实现一个Laravel自定义缓存驱动,我们大致需要分三步走:定义你的缓存存储逻辑、注册这个驱动、以及配置Laravel来使用它。

第一步:定义自定义缓存存储类

你需要创建一个类,它负责实际的缓存操作,比如数据的存、取、删除。这个类必须实现Illuminate\Contracts\Cache\Store接口。这个接口定义了所有缓存驱动需要实现的方法,比如getputforgetflush等。

我们以一个非常简化的文件系统缓存为例,但请注意,实际项目中你可能对接的是一个内部的KV存储、一个特定的数据库表,或者其他非标准后端。

<?php

namespace App\Cache;

use Illuminate\Contracts\Cache\Store;
use Carbon\Carbon; // Laravel自带的日期处理库,方便计算过期时间

class MyCustomCacheStore implements Store
{
    protected string $path;
    protected string $prefix;

    public function __construct(string $path, string $prefix = '')
    {
        $this->path = $path;
        $this->prefix = $prefix;
        if (!is_dir($this->path)) {
            mkdir($this->path, 0777, true);
        }
    }

    /**
     * 获取缓存项的值。
     */
    public function get($key): mixed
    {
        $filePath = $this->getFilePath($key);
        if (!file_exists($filePath)) {
            return null;
        }

        $content = file_get_contents($filePath);
        $data = json_decode($content, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            // 文件内容损坏,或者不是有效的JSON
            $this->forget($key); // 清理掉损坏的缓存
            return null;
        }

        if (isset($data['expires']) && $data['expires'] !== null && Carbon::now()->timestamp > $data['expires']) {
            $this->forget($key); // 已过期
            return null;
        }

        return $data['value'] ?? null;
    }

    /**
     * 获取多个缓存项的值。
     */
    public function many(array $keys): array
    {
        $results = [];
        foreach ($keys as $key) {
            $results[$key] = $this->get($key);
        }
        return $results;
    }

    /**
     * 将数据存入缓存。
     *
     * @param string $key 缓存键
     * @param mixed $value 缓存值
     * @param int $minutes 缓存分钟数
     */
    public function put($key, $value, $minutes): bool
    {
        $filePath = $this->getFilePath($key);
        $expires = $minutes === 0 ? null : Carbon::now()->addMinutes($minutes)->timestamp;

        $data = json_encode([
            'value' => $value,
            'expires' => $expires,
        ]);

        return file_put_contents($filePath, $data) !== false;
    }

    /**
     * 将多个数据存入缓存。
     */
    public function putMany(array $values, $minutes): bool
    {
        $success = true;
        foreach ($values as $key => $value) {
            if (!$this->put($key, $value, $minutes)) {
                $success = false;
            }
        }
        return $success;
    }

    /**
     * 永久存储数据到缓存。
     */
    public function forever($key, $value): bool
    {
        return $this->put($key, $value, 0); // 0分钟表示永不过期
    }

    /**
     * 增加一个缓存项的值。
     *
     * 注意:对于文件缓存,这通常不是原子操作,在高并发下可能存在问题。
     */
    public function increment($key, $value = 1): int|bool
    {
        $current = (int) $this->get($key);
        $new = $current + $value;
        $this->put($key, $new, 0); // 重新存入,并保持永不过期或原有TTL
        return $new;
    }

    /**
     * 减少一个缓存项的值。
     */
    public function decrement($key, $value = 1): int|bool
    {
        $current = (int) $this->get($key);
        $new = $current - $value;
        $this->put($key, $new, 0);
        return $new;
    }

    /**
     * 从缓存中删除一个项。
     */
    public function forget($key): bool
    {
        $filePath = $this->getFilePath($key);
        if (file_exists($filePath)) {
            return unlink($filePath);
        }
        return true;
    }

    /**
     * 清空所有缓存。
     */
    public function flush(): bool
    {
        $files = glob($this->path . '/' . $this->prefix . '*.cache');
        foreach ($files as $file) {
            unlink($file);
        }
        return true;
    }

    /**
     * 获取缓存键的前缀。
     */
    public function getPrefix(): string
    {
        return $this->prefix;
    }

    /**
     * 获取缓存文件的完整路径。
     */
    protected function getFilePath(string $key): string
    {
        // 使用md5是为了避免文件名过长或包含特殊字符,同时保持唯一性
        return $this->path . '/' . $this->prefix . md5($key) . '.cache';
    }
}
登录后复制

第二步:注册自定义缓存驱动

存了个图
存了个图

视频图片解析/字幕/剪辑,视频高清保存/图片源图提取

存了个图17
查看详情 存了个图

我们需要创建一个服务提供者(Service Provider),在它的boot方法中,利用Cache::extend方法来注册我们的自定义驱动。

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;
use App\Cache\MyCustomCacheStore; // 引入我们自定义的缓存存储类

class CustomCacheServiceProvider extends ServiceProvider
{
    /**
     * 注册任何应用服务。
     */
    public function register(): void
    {
        //
    }

    /**
     * 引导任何应用服务。
     */
    public function boot(): void
    {
        // 扩展缓存管理器,注册名为 'mycustom' 的驱动
        Cache::extend('mycustom', function ($app, $config) {
            // $config 包含了 'mycustom' 驱动在 config/cache.php 中的配置
            // 在这里,我们可以根据配置创建并返回我们的 MyCustomCacheStore 实例
            $path = $config['path'] ?? storage_path('framework/cache/mycustom');
            $prefix = $config['prefix'] ?? '';

            return new MyCustomCacheStore($path, $prefix);
        });
    }
}
登录后复制

别忘了在config/app.php文件的providers数组中注册这个服务提供者:

    'providers' => [
        // ...
        App\Providers\CustomCacheServiceProvider::class,
    ],
登录后复制

第三步:配置Laravel使用自定义驱动

config/cache.php文件中,添加你的自定义驱动配置。

<?php

return [

    //
登录后复制

以上就是Laravel自定义缓存驱动?缓存扩展如何实现?的详细内容,更多请关注php中文网其它相关文章!

驱动精灵
驱动精灵

驱动精灵基于驱动之家十余年的专业数据积累,驱动支持度高,已经为数亿用户解决了各种电脑驱动问题、系统故障,是目前有效的驱动软件,有需要的小伙伴快来保存下载体验吧!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号