berny/cache

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

通用缓存任务的统一工具集

1.0 2014-10-20 22:23 UTC

This package is not auto-updated.

Last update: 2024-02-26 08:10:22 UTC


README

此库提供了一套用于通用缓存任务的统一工具。

SensioLabsInsight

特性

从经典缓存接口迁移到项接口。

安装

composer/packagist

  • "berny/cache": "*@dev" 添加到您的 composer.json 文件

github

存储

您想在某个地方存储缓存数据,这里就是 StorageInterface 发挥作用的地方。

它的唯一职责是通过 getItem($key) 方法从键创建项。

该接口的一些实现包括:

  • FilesystemStorage
  • MemoryStorage
  • DoctrineCacheAdapter

项允许在给定的存储中管理一个键。您可以:

  • key(): 获取项的键
  • get(): 获取其缓存值(如果未错过缓存)
  • set($value): 设置缓存值
  • miss(): 检查是否错过缓存
  • remove(): 清除它

示例

function cacheComplexFunction(ItemInterface $item, Closure $complex)
{
    if ($item->miss()) {
        $value = $complex($item->key());
        $item->set($value);
    }
    return $item->get();
}

$storage = new MemoryStorage();
$result = cacheComplexFunction($storage->getItem('key'), complexCalculation);

缓存

主要大脑是 Cache,一个具体类,它接收一个 StorageInterface(可选的 StrategyInterface)来代理所有请求。它定义了:

  • get($key, $default = null): 通过键的普通获取,在缓存未命中时返回 $default
  • getOrSet($key, $value): 通过键获取缓存值,在缓存未命中时存储和返回 $value
  • getOrLazySet($key, $callback): 与 getOrSet 相同,但在缓存未命中时对 $callback 进行延迟评估。
  • set($key, $value): 没有什么秘密,一个普通的键设置。
  • remove($key): 仅在未错过缓存时删除项。
  • getItem($key): 返回由底层的 StorageInterface 创建的 ItemInterface

示例

// Storage is any StorageInterface implementation
$cache = new Cache($storage);

$result = $cache->get('key_1'); // null on cache misses
$result = $cache->get('key_2', 'default'); // 'default' on cache misses
$result = $cache->getOrSet('key_3', 'value'); // 'value' stored on cache misses
$result = $cache->getOrLazySet('key_4', $callback); // $callback called only on cache misses

策略

实现 StrategyInterface 来自动生成从任何用户域键到具体键的生成。这允许自动缓存失效。

如果注入到 Cache 中,键将首先通过此对象调用 setItem($key)

实现

  • 文件系统策略:将键视为路径文件名。在文件更改时返回带有最后修改时间的键以使缓存条目失效。

示例

$path = __DIR__ . '/to-do/';
$strategy = new FilesystemStrategy();
// Storage is any StorageInterface implementation
$cache = new Cache($storage, $strategy);
// Callback only called the first time and every time the $path content changes
$cache->getOrLazySet($path, $callback);