giver / cacheable
Laravel 5 的查询缓存
Requires
- php: >=5.4.0
- illuminate/database: v5.1.16.2
- illuminate/support: ~5.0
Requires (Dev)
- mockery/mockery: 0.9.*
- phpunit/phpunit: 4.2.*
This package is not auto-updated.
Last update: 2024-09-20 17:58:05 UTC
README
Cacheable 是 Laravel 5.0+ 的 Eloquent 特性,它重新引入了 Laravel 4.2 中的 cache()
查询函数。这使得缓存查询结果变得非常容易,缓存时间可调整。
// Get a the first user's posts and cache them for a day.
User::first()->cache(1440)->posts()->get();
它通过简单地缓存所使用的 SQL 查询并存储结果来实现。如果在缓存持续期间尝试相同的查询,则将从中检索缓存结果,而不是再次访问数据库。
安装
使用 Composer 安装,就像安装任何其他东西一样。
composer require giver/cacheable
开始使用 Eloquent 的最简单方法是创建一个抽象的 App\Model
,您可以从中扩展您的应用程序模型。在这个基础模型中,您可以导入 cacheable 特性,这将扩展任何基于您的模型构建的查询的相同缓存功能。
<?php
namespace App;
use Giver\Cacheable\Cacheable;
use Illuminate\Database\Eloquent\Model as Eloquent;
abstract class Model extends Eloquent
{
use Cacheable;
}
现在,只需确保从新的 App\Model
而不是 Eloquent 使用您的应用程序模型。
<?php
namespace App;
class Post extends Model
{
//
}
或者,您可以直接将特性应用于您希望使用 cache()
的每个模型。
用法
使用缓存方法非常简单。只需传递您希望将查询结果存储在缓存中的分钟数,只要在该时间段内调用相同的查询,结果就会从缓存中检索,而不是再次从数据库中检索。
// Cache the number of users for an hour.
$users = User::cache(60)->count();
缓存标签
如果您想对某些查询进行标记,可以在您的查询中添加 cacheTags('tag_name')
。请注意,缓存标签不是所有缓存驱动器都支持。
// Cache the number of users for an hour and tag it with 'user_queries'
User::cache(60)->cacheTags('user_queries')->count();
缓存前缀
如果您希望为每个查询的缓存键添加一个唯一的前缀(例如,如果您的缓存不支持标记),可以在您的查询中添加 prefix('prefix')
。
// Cache the number of users for an hour and prefix the key with 'users'
User::cache(60)->prefix('users')->count();
或者,您可以将 ``$cacheCachePrefix` 属性添加到您的模型中,以始终使用该缓存前缀。
模型级别的缓存标签
您可以通过将 $cacheCacheTag
属性设置为用于标记查询的唯一字符串来为模型的全部查询设置缓存标签。
关系
验证通过基于查询的缓存查询来实现。这意味着当您执行预加载时,除非显式指定,否则这些额外查询不会缓存。您可以通过使用回调与您的预加载一起做。
$users = User::where("id", ">", "1")
->with(['posts' => function ($q) { $q->cache(10); }])
->cache(10)
->take(5)
->get();
始终启用
您可以通过将 $cacheFor
属性设置为要缓存结果的分钟数来选择缓存模型的全部查询。请谨慎使用此功能,因为如果您不了解其工作方式,可能会导致意外的行为和应用程序中的过时数据。
缓存刷新
根据包的架构,无法删除单个查询的缓存。但如果您使用缓存标签标记了任何查询,您能够刷新该标签的缓存。
User::flushCache('user_queries');
如果您使用了 $cacheCacheTag
属性,您可以使用不带参数的方法,并刷新由 $cacheCacheTag
设置的标签的缓存。
User::flushCache();