jameslkingsley/laravel-scoped-cache

无需附加ID即可轻松缓存特定于您Eloquent模型的项。

1.0.0 2019-05-10 15:44 UTC

This package is auto-updated.

Last update: 2024-09-11 14:53:37 UTC


README

此包添加了一个特性,该特性为与您的应用程序缓存交互提供了cache方法,但仅限于您的Eloquent模型。这消除了在缓存键中不断附加模型ID的需求。只需像这样访问缓存:$user->cache('Avatar')

底层它将在缓存键前缀中添加一个生成的特定于模型的键,格式为Model_ID:your-key。您可以通过在模型上实现getScopedCacheKey方法来完全覆盖此格式。

安装

您可以通过composer安装此包

composer require jameslkingsley/laravel-scoped-cache

使用方法

导入特性并在任何Eloquent模型上使用它。您还可以在非eloquent类上使用它,前提是它们有一个返回其唯一引用的getKey方法。

use Kingsley\ScopedCache\ScopedCache;

class User extends Model
{
    use ScopedCache;
}

现在您可以像平常一样使用缓存。您可以直接从cache方法设置/获取项,或者通过留空参数列表来调用任何其他缓存方法。

$user->cache(['name' => $user->name], 5);
$user->cache('name', 'default name');

$user->cache()->remember('name', 5, function () {
    // $this refers to the model this cache instance is scoped to
    return $this->name;
});

请注意,此包期望代理调用缓存的第一参数为缓存键。在某些情况下,自定义宏可能会破坏此格式。