authentik/eloquent-cache

轻松缓存 Laravel 的 Eloquent 模型

1.3.2 2023-04-21 17:04 UTC

README

轻松缓存 Laravel 的 Eloquent 模型。

Build Status Coverage Status Latest Stable Version Total Downloads

要求

  • PHP >= 7.2

  • Laravel 6 / 7 / 8

安装

通过 composer 安装

composer require authentik/eloquent-cache

工作原理

  • 当 Eloquent 获取模型时,模型实例的 JSON 表示将被缓存。

  • 随后,当 Eloquent 通过 ID 获取模型时,缓存的 JSON 将被转换回实例。

用法

在您想要缓存的模型中使用 Cacheable 特性。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Authentik\EloquentCache\Cacheable;

class Category extends Model
{
    use Cacheable;


    /*
     * You can optionally override the following functions:
     */
    
    // Time To Live in minutes (default value: 0 => no TTL)
    public function getCacheTTL() {
        return 60;
    }

    // default value: the lowercase name of the model
    public function getCacheTagName() {
        return 'cat';
    }

    // Cache busting will automatically invalidate the cache when model instances are updated or deleted.
    // default value: true
    public function isCacheBustingEnabled() {
        return false;
    }

    // Whether or not to keep model instances in a static array cache
    //  (useful to avoid querying the cache store/building instances from json multiple times)
    // default value: true
    public function isStaticCacheEnabled() {
        return false;
    }
}

要手动缓存模型实例,请使用 cache 方法。

Category::find(1)->cache();

要使模型实例的缓存无效,请使用 refreshflush 方法。

$refreshedInstance = Category::find(1)->refresh();

// or

Category::flush(Category::find(1));

要使模型的所有实例的缓存无效,请使用 flush 方法。

Category::flush();

变更日志

点击这里