LaraCache 是一个基于 ORM 的 Laravel 包, 用于基于模型查询创建、更新和管理缓存项。使用此包,您可以缓存在整个应用程序中大量使用的查询。

use Mostafaznv\LaraCache\TrAIts\LaraCache;

class Article extends Model
{
    use LaraCache;

    public static function cacheEntities(): array
    {
        return [
            CacheEntity::make('list.forever')
                ->cache(function() {
                    return Article::query()->latest()->get();
                }),

            CacheEntity::make('latest')
                ->validForRestOfDay()
                ->cache(function() {
                    return Article::query()->latest()->first();
                })
        ];
    }
}

使用 cacheEntities 方法来定义缓存的查询,Laracache 会处理剩下的事情。要使用缓存查询,您将调用模型,如下例所示:

use Mostafaznv\LaraCache\Facades\LaraCache;

$cache = Article::cache()->get('latest');
// 或者
$cache = LaraCache::retrieve(Article::class, 'latest');

使用此软件包,您可以使用以下功能控制缓存:

  • 启用/禁用缓存
  • 手动更新缓存
  • 手动更新所有缓存实体
  • 删除缓存
  • 使用 fluent 方法或 ttl()方法控制CacheEntity 持续时间

我认为以下手动缓存更新方法很简洁,可以即时刷新缓存:

Article::cache()->update('latest');2// or3LaraCache::update(Article::class, 'latest');

您可以了解此软件包、获取完整的安装说明,并在 GitHub 上查看 源代码 。

原文地址:https://laravel-news.com/laracache-orm-caching-package-for-laravel

译文地址:https://learnku.com/laravel/t/68860

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。