mosamy / cacheable

Laravel 缓存模型的包

1.0.2 2023-03-26 22:04 UTC

This package is auto-updated.

Last update: 2024-09-27 05:10:23 UTC


README

Laravel Eloquent 模型缓存

安装

composer require mosamy/cacheable

用法


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;
}

// this will get records from database.
$posts = Posts::get();

// this will get records from cache.
$posts = Posts::getCached();

//in shortcut
$posts = getCached('posts');

要在缓存结果中搜索,可以使用以下代码

$posts = Posts::getCached()->searchCached('keyword', ['name', 'description']);

要设置默认缓存搜索属性,请使用此函数


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;

  public static function searchableAttributes(){
    return ['name', 'description'];
  }

}

$posts = Posts::getCached()->searchCached('keyword');

如果您需要缓存具有关联或自定义查询的模型,您应该重写此函数


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;

  public static function cache(){
    return self::with('category')->get();
  }

}

默认情况下,缓存名称的格式为: prefix(连接名称)(表名称)。默认情况下,缓存名称没有前缀。如果您想设置缓存前缀,应重写此方法。


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;

  public static function cache_prefix(){
    return 'cache_';
  }

}

因此,默认名称将是“cache_mysql_posts”

要删除缓存,您可以使用此方法

Post::deleteCache();

或简单地清除所有缓存

php artisan cachhe:clear