curder/laravel-query-cache

缓存所有 {select} 查询或仅特定 Eloquent 模型的重复查询

5.0.0 2024-04-22 06:23 UTC

This package is auto-updated.

Last update: 2024-09-22 07:23:54 UTC


README

缓存所有 "select" 查询或仅特定 Eloquent 模型的重复查询

Build Status StyleCI Scrutinizer Code Quality

概览

此包允许您缓存所有类型为 select 的查询,或仅缓存特定 Eloquent 模型的重复查询。

请注意,由于使用了缓存标签,因此“文件”或“数据库”缓存驱动程序与该包不兼容。

兼容的缓存存储:数组,redis,apc,memcached
测试的缓存存储:数组,redis

安装

通过 Composer 安装包

composer require curder/laravel-query-cache

使用以下命令发布配置文件

php artisan vendor:publish --provider="Neurony\QueryCache\ServiceProvider" --tag="config"

请阅读 config/query-cache.php 配置文件注释,因为它包含额外信息

用法

步骤 1

您的 Eloquent 模型应使用 Neurony\QueryCache\Traits\IsCacheable 特性。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Neurony\QueryCache\Traits\IsCacheable;

class YourModel extends Model
{
    use IsCacheable;
}
步骤 2

在您的 .env 文件中添加必要的环境变量

# The driver used for storing the cache keys that this package generates.
# This driver can differ from your main Laravel's CACHE_DRIVER.
QUERY_CACHE_DRIVER=redis

# Wether to cache absolutely all queries for the current request.
CACHE_ALL_QUERIES=true

# Wether to cache only the duplicated queries for the current request.
CACHE_DUPLICATE_QUERIES=true

根据您设置的环境变量方式,下次在 Eloquent 模型上执行 select 查询时(首次运行之后),查询将被缓存。

额外

使用 QueryCacheService

请注意,Neurony\QueryCache\Services\QueryCacheService 类是实现 Neurony\QueryCache\Contracts\QueryCacheServiceContract 接口的实际实现。

Neurony\QueryCache\Services\QueryCacheService 类绑定到 Laravel 的 IoC 并作为单例,别名为 cache.query

因此,直接使用 Neurony\QueryCache\Services\QueryCacheService 的推荐方法是

app('cache.query');

// or

app(QueryCacheServiceContract::class);
启用/禁用查询缓存

您可以通过调用 Neurony\QueryCache\Services\QueryCacheService 类上存在的 enableQueryCachedisableQueryCache 方法来启用或禁用当前请求的所有查询缓存。

// from her on, no queries will be cached
app('cache.query')->disableQueryCache();

/*
make your queries
the queries up until now won't be cached
*/

// from her on, apply query caching
app('cache.query')->enableQueryCache();

/*
make your queries
this queries will be cached
*/

致谢

安全

如果您发现任何安全问题,请通过电子邮件 andrei.badea@neurony.ro 反馈,而不是使用问题跟踪器。

许可

MIT 许可证(MIT)。有关更多信息,请参阅 LICENSE

变更日志

请参阅 CHANGELOG 了解最近的变化。

贡献

请参阅 CONTRIBUTING 了解详细信息。