plug2team/model-cacheable

v0.5.1 2020-04-21 19:37 UTC

This package is auto-updated.

Last update: 2024-09-24 13:48:41 UTC


README

用于控制模型缓存的包。

安装

composer require plug2team/model-cached

安装包后,导入配置文件

php artisan vendor:publish --tag=config

配置模型

为了让模型被缓存观察,只需在其模型上应用 trait Cacheable

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Plug2Team\ModelCached\Concerns\Cacheable;

class User extends Authenticatable
{
    use Cacheable;

AppServiceProviderboot 方法中注册模型

    public function boot() {
        \App\User::crape();
    }

实用工具

Console/Kernel.php 中注册辅助命令。

 $schedule->command('cacheable:flush')->cron(config('model_cached.commands.flush'));
 $schedule->command('cacheable:reindex')->cron(config('model_cached.commands.re_index'));

工作原理

经过一些测试后,我发现通过分组管理记录的持久性更简单、更高效。

分组的工作原理如下

  1. 将模型名 App\User 转换为 user

  2. 得到名称后,我们创建名为 user.indexes 的索引组,用于存储和管理通过 Eloquent 事件接收到的 ids

  3. 有了这些索引,下一步是创建默认的分组,组 all 可以通过 app('cacheable')->index('App\User')->group('all')->retrieve() 获取;另一种获取该分组的方法是在模型中直接调用 \App\User::cache('all')

  4. 要捕获与组关联的索引,可以使用 app('cacheable')->index('App\User')->group('all')->getIndexes()app('cache')->get('cached.{model}.{group}');这会返回与组关联的 id 列表。

恢复索引

键结构是 .id

恢复分组

注册模型后,我们开始监控 Eloquent 的事件:saveddeletedretrieved

要恢复分组,只需在

$users = \App\User::cache('all');

默认注册了 all 组,其他组可以使用其键树注册。