rogervila/laravel-autocache

自动缓存 Laravel Eloquent 模型

0.5.0 2020-10-05 11:59 UTC

README

Laravel Autocache

Build Status Build status StyleCI Quality Gate Status Coverage Maintainability Rating Latest Stable Version Total Downloads License

Laravel Autocache

关于

Laravel Autocache 包缓存 Eloquent 模型的 'select' 查询。

当模型通过 Eloquent 方法 被修改时,缓存会自动刷新。

示例

想象一下,我们使用 Eager Loading 通过类别选择所有帖子

Post::with('categories')->get();

这将生成两个查询,只运行一次

select * from `posts`
select * from `categories`

在没有对帖子或类别模型进行更改的情况下,这两个查询将被缓存。

现在,想象一下我们编辑了我们最新帖子的标题

$post = Post::find($id);
$post->update(['title' => 'Your edited title']);

return Post::with('categories')->get();

只有对 posts 表的 select 查询将被执行,因为类别模型仍然被缓存

select * from `posts`

在必要时,可以在运行时禁用 Autocache

Post::disableAutoCache();

// Do your database changes here

Post::enableAutoCache();

安装

使用 composer 需要此包。

composer require rogervila/laravel-autocache

如果您不使用自动发现,请将 ServiceProvider 添加到 config/app.php 中的 providers 数组中

LaravelAutoCache\AutocacheServiceProvider::class,

现在,使用发布命令将包配置复制到您的项目配置中

php artisan vendor:publish --provider=" LaravelAutoCache\AutocacheServiceProvider"

用法

首先,将您要处理的模型放入 config/autocache.php 文件的 models 键中。

/**
 * List of models that implement autocache by default.
 * Models have to also implement the Autocache trait
 * in order to work properly
 */
'models' => [
    App\Product::class,
],

然后,在配置中列出的模型上添加 Autocache 特性

namespace App;

use Illuminate\Database\Eloquent\Model;
use LaravelAutoCache\Autocache;

class Product extends Model
{
    use Autocache;
    ...

故障排除

Autocache 在更新查询上不起作用

查看这个 Laravel 问题评论

许可证

Laravel Autocache 是开源软件,根据 MIT 许可证 授权。

图标由 Dirtyworkswww.flaticon.com 创建,根据 CC 3.0 BY 许可。