sci/cacheable

透明缓存库

1.0.1 2016-02-21 18:40 UTC

This package is auto-updated.

Last update: 2024-09-09 00:06:56 UTC


README

Build Status Build Status

安装

使用 composer

composer require sci/cacheable

使用

比如说,你有一个类 Foo,它实现了一个方法 Foo::bar(),这个方法的时间/资源消耗相当高

class Foo
{
    public function bar($a, $b)
    {
        // make some hard things with $a and $b
        ...
        
        return ...; // some result
    }
}

$foo = new Foo();

$bar = $foo->bar(1, 2); // takes some amount of time

// and later, again...
$bar = $foo->bar(1, 2); // takes the same amount of time, again

如果没有副作用,那么 Foo::bar() 的结果只由它的参数 $a$b 决定。所以,如果你再次调用这个方法,可以使用一些缓存。为了避免与缓存键混搭,你可以使用 sci\cacheable

use Sci\Cacheable;
use Sci\CacheTrait;

class Foo implements Cacheable
{
    use CacheTrait;

    public function bar($a, $b)
    {
        // make some hard things with $a and $b
        ...
        
        return ...; // some result
    }
}

$foo = new Foo();
$foo->setCache(/* any PSR-6 cache pool interface */)

$bar = $foo->cache()->bar(1, 2); // 1st call takes some time, but now, the result is stored into cache

// and later, again...
$bar = $foo->cache()->bar(1, 2); // 2nd call's result comes directly from cache

详细说明

  • 要被缓存的类(如上面的示例中的 Foo)实现了接口 Sci\Cacheable(它需要一个 cache() 方法)。
  • 这可以通过使用 Sci\CacheTrait(它还提供了一个 setCache() 方法)来实现。
  • setCache 方法接收的第一个参数是一个实现 Psr\Cache\CacheItemPoolInterface 的服务。
    • 这个缓存池实际上是缓存后端。
    • setCache 的可选第二个参数是所有缓存的默认 TTL(存活时间)。
  • 要使用缓存,方法调用将通过 cache() 方法进行代理,例如,现在我们使用 $foo->cache()->bar(1, 2) 而不是 $foo->bar(1, 2)
    • cache() 方法返回 $this,即它以透明的方式操作(流畅接口)。
    • cache() 的可选参数允许指定与默认值不同的 TTL。

实现

许可证

此包的所有内容均受 MIT 许可证 许可。