Laravel扩展推荐:ORM 缓存包 “LaraCache”

来自:互联网
时间:2022-10-16
阅读:

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

返回顶部
顶部