itsoneiota/cache

One iota 缓存库。

1.17 2020-05-06 13:11 UTC

README

概述

简单接口,用于缓存源。

Cache 类封装了一个 Memcached 实例,添加了键值映射和默认过期时间。

安装

要自动加载此包及其依赖项,最佳方式是包含标准的 Composer 自动加载器,即 vendor/autoload.php

测试

可以通过从存储库根目录调用 vendor/bin/phpunit 来运行库的单元测试套件。

基本用法

use \itsoneiota\cache;

$mc = new \Memcached();
// Configure memcached…

$cache = new Cache($mc);

$cache->set('foo', 'bar'); // Caches a value of 'bar' against the key of 'foo'.
$cache->get('foo'); // Returns 'bar'.

缓存键前缀

如果您想避免缓存键冲突,可以初始化带有键前缀的缓存,这将在获取、设置和删除时添加到所有键。例如

use \itsoneiota\cache;

$mc = new \Memcached();
// Configure memcached…

$cache = new Cache($mc, 'myStore');

$cache->set('foo', 'bar'); // Caches a value of 'bar' against the key of 'myStore.foo'.
$cache->get('foo'); // Returns 'bar'.

默认过期时间

创建缓存时,您可以指定默认的生存时间,用于添加和设置。可以通过指定显式的过期时间来覆盖。

use \itsoneiota\cache;

$mc = new \Memcached();
// Configure memcached…

$cache = new Cache($mc, 'myStore', 120);

$cache->set('foo', 'bar'); // Caches for 2 minutes (the default).
$cache->set('bat', 'baz', 30); // Caches for 30 seconds.

加密缓存内容

SecureCacheCache 的一个子类,它使用双向加密来加密其内容。

use \itsoneiota\cache;

$mc = new \Memcached();
// Configure memcached…

$cache = new SecureCache($mc, 'myTopSecretEncryptionKey');

如果您需要在 SecureCache 中前缀键,您始终可以调用 $cache->setKeyPrefix('myPrefix')

奖金缓存(Cacheback)

内存缓存前端

如果您可能在请求内对缓存进行多次调用,可能调用到相同的值,InMemoryCacheFront 可以通过在 Cache 实例之上提供一个读-写缓存来防止对 Memcached 服务器的非必要网络调用。默认情况下,内存中保留的项目数限制为 100,但可以通过构造函数参数进行更改。

use \itsoneiota\cache;

$mc = new \Memcached();
// Configure memcached…

$cache = new Cache($mc, 'myStore', 120);

$superFastCache = new InMemoryCacheFront($cache, 1000); // Store 1000 items in local memory.

内存缓存

如果您需要模拟缓存,而不需要 Memcached 服务器,InMemoryCache 将完成这项工作。它看起来就像一个 Cache,但它将所有内容都保存在一个普通的 PHP 数组中。

模拟缓存

为了测试目的,MockCache 模拟了一个缓存,并允许您检查值是否已设置以及它们的过期时间,而无需通过使用 PHPUnit 模拟来经历所有麻烦。《getExpiration()` 允许您检查键的过期时间。《timePasses()` 允许您模拟时间的流逝,通过给定秒数推进并相应地使缓存项目过期。

use \itsoneiota\cache;

$cache = new MockCache();

$cache->set('foo', 'bar', 60);
$cache->get('foo'); // Returns 'bar'.

$cache->timePasses(61);

$cache->get('foo'); // Returns NULL.

待办事项…

我可能很快就会添加的事情

  • 检查并设置操作
  • 防止缓存堆叠