pulkitjalan/cacheable

此包已被弃用且不再维护。未建议替代包。

使用 find 方法自动缓存 Eloquent 模型

0.2.0 2016-02-14 08:33 UTC

This package is auto-updated.

Last update: 2019-09-06 07:07:41 UTC


README

使用 find 方法自动缓存基本 Eloquent 模型

License Latest Version Total Downloads

要求

  • PHP >= 5.5.9
  • Laravel >= 5.1

安装

通过 composer 安装 - 在终端中

composer require pulkitjalan/cacheable

此包使用了 pulkitjalan\multicache,它需要一个服务提供者注册。所以将以下代码添加到您的 config/app.php 中的 providers 数组

PulkitJalan\Cache\Providers\MultiCacheServiceProvider::class

用法

只需在任何您希望自动缓存模型的模型中使用 Cacheable 特性。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use PulkitJalan\Cacheable\Cacheable;

class CachedModel extends Model
{
    use Cacheable;
}

只有使用 findfindManyfindOrFail 方法时,模型缓存才有效。

如果您希望有类似于 Laravel 4 的缓存行为,则可以考虑使用 dwightwatson/rememberable,它将 remember 函数添加回 Eloquent。这两个包也可以一起使用。

您可以选择设置模型的过期时间(以分钟为单位),默认为 1440 分钟(24小时)。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use PulkitJalan\Cacheable\Cacheable;

class CachedModel extends Model
{
    use Cacheable;

    /**
     * Set the cache expiry time.
     *
     * @var int
     */
    public $cacheExpiry = 60;
}

模型使用模型的 表名 作为缓存标签和 id 作为键进行缓存。特性和观察者被注册以在 saveddeleted 时从缓存中删除。

仅对基本模型(没有添加任何条件)应用缓存。

// cached
CachedModel::find(1);

// not cached
CachedModel::where('some_field', 1)->find(1);

// not cached
CachedModel::with('relation')->find(1);

可以通过在 Cacheable 特性中调用新的 refresh 方法来手动清除缓存,该方法可以在缓存模型中找到。

// manually clear cache
CachedModel::find(1)->refresh();