alex433/laravel-eloquent-cache

Laravel的Eloquent模型缓存

v0.9.1 2024-03-26 08:32 UTC

This package is auto-updated.

Last update: 2024-09-26 09:35:29 UTC


README

Total Downloads Latest Stable Version Latest Unstable Version License

Laravel的Eloquent模型缓存

安装

通过composer 安装

composer require alex433/laravel-eloquent-cache

工作原理

当Eloquent通过主键获取模型时,SQL查询结果将被缓存。随后,当Eloquent再次通过主键获取模型时,将使用缓存结果。当您创建、更新或删除模型实例时,缓存条目将被清除。

用法

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Alex433\LaravelEloquentCache\Cachable;

class Post extends Model
{
    use Cachable;
}

在以下情况下,将执行缓存查询而不是SQL查询。它也适用于"属于"关系。

Post::find($id); // findOrFail(), findOrNew()
Post::where('id', $id)->first(); // firstOrFail(), firstOrNew(), firstOrCreate(), firstOr()
Post::whereId($id)->first();
Post::where('id', $id)->get();

您可以定义以下属性来更改默认特性的行为。

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

use Alex433\LaravelEloquentCache\Cachable;

class User extends Authenticatable
{
    use Notifiable,
        Cachable;

    /**
     * Cache TTL in seconds. Defaults indefinitely
     *
     * @var int $cacheTtl
     */
    public $cacheTtl = 3600;

    /**
     * Cache store name. Defaults default cache connection
     *
     * @var string $cacheStore
     */
    public $cacheStore = 'redis';

    /**
     * Cache tags. Defaults no tags
     *
     * @var array $cacheTags
     */
    public $cacheTags = ['users'];
}

要使模型实例的缓存条目失效,请使用forget方法。

User::find($id)->forget();

// or

User::find($id)->forget()->refresh();

当使用缓存标签时,您可以使用flushCache方法清除模型的缓存。

User::flushCache();

// or

User::find($id)->flushCache();