yateric/cacheable

使任何对象方法返回可缓存。

v1.0.3 2017-01-03 04:58 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:25:54 UTC


README

Build Status Software License Total Downloads Latest Version

此独立包通过添加链式方法使任何对象方法返回可缓存。

特性

  • 使任何(静态或非静态)对象方法调用可缓存
  • 指定缓存时长
  • 独立包,您可以在不使用任何框架的情况下使用它
  • 支持Laravel 5+(无需额外配置)

安装

需要PHP 5.5+ 或 HHVM 3.6+。

要获取Cacheable的最新版本,只需使用Composer引入项目。

$ composer require yateric/cacheable

当然,您也可以手动更新require块并运行composer update

{
    "require": {
        "yateric/cacheable": "^1.0"
    }
}

用法

首先,将Yateric\Cacheable\Cacheable特质引入您想要缓存方法结果的类中,这可以是任何类型的类:Eloquent模型、仓库或简单的对象。

use Yateric\Cacheable\Cacheable;

class Worker {
    use Cacheable;
    
    public function timeConsumingTask()
    {
        sleep(10);
        
        return 'Some results';
    }
}

现在,您可以通过添加链式方法cache()来缓存并返回timeConsumingTask()的结果。

$worker = new Worker;

// By default, the results will cache for 60 minutes.
$results = $worker->cache()->timeConsumingTask();

静态方法返回缓存

use Yateric\Cacheable\Cacheable;

class Worker {
    use Cacheable;
    
    public static function timeConsumingTaskInStatic()
    {
        sleep(10);
        
        return 'Some results';
    }
}

// By default, the results will cache for 60 minutes.
$results = Worker::cacheStatic()->timeConsumingTaskInStatic();

特定缓存时长

// Cache result for 120 minutes.
$results = $worker->cache(120)->timeConsumingTask();
$results = Worker::cacheStatic(120)->timeConsumingTaskInStatic();

缓存时长层级

这里有三个级别的缓存时长设置

  • 运行时级别
  • 实例级别
  • 全局级别

以下是一些示例

use Yateric\Cacheable\CacheDecorator;

// Cache for 60 minutes by default.
$workerA->cache()->timeConsumingTask();

// Cache for 120 minutes by runtime setting.
$workerA->cache(120)->timeConsumingTask();

// Return to default 60 minutes.
$workerA->cache()->timeConsumingTask();

// Set default cache duration to 180 minutes.
$workerA->cache()->setDefaultCacheMinutes(180);

// These calls will cache for 180 minutes.
$workerA->cache()->timeConsumingTaskA();
$workerA->cache()->timeConsumingTaskB();
$workerA->cache()->timeConsumingTaskC();

// Set the global cache duration to 240 minutes.
CacheDecorator::setGlobalCacheMinutes(240);

// Worker A will remain cache for 180 minutes because 
// we have set the default cache duration in instance level.
$workerA->cache()->timeConsumingTask();

// These calls will cache for 240 minutes.
$workerB->cache()->timeConsumingTask();
$workerC->cache()->timeConsumingTask();

更换底层缓存存储

如果您使用Laravel 5+,Cacheable将自动使用默认缓存存储config('cache.default')。但您可以通过调用setCacheStore()指定任何实现了Illuminate\Contracts\Cache\Store接口的缓存存储。

use Yateric\Cacheable\CacheDecorator;

CacheDecorator::setCacheStore(new RedisStore($redis));

缓存前缀

您可以通过调用setCachePrefix()手动设置缓存前缀。

use Yateric\Cacheable\CacheDecorator;

CacheDecorator::setCachePrefix('yourprefix_');

安全

如果您在此包中发现安全漏洞,请发送电子邮件至yateric@gmail.com。所有安全漏洞都将得到及时解决。

许可

Cacheable遵循MIT许可证(MIT)