ds/easy-cache

PHP PSR 16 缓存组件

1.0.0 2021-09-18 00:30 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:29:43 UTC


README

关于 PSR-16 的更多信息,请访问 psr/simple-cache

安装

使用 Composer 安装组件

$ composer require ds/easyCache "^v1.0.0"

用法

保存到缓存

$cache->set(string $key, mixed $value, DateInterval $expires)
  • $key - string 缓存键必须是有效的字符串。

  • $value - mixed 要存储在缓存中的数据

  • $expires - DateInterval|int|null 如果为 null,则使用默认过期时间。

$cache->setMultiple($values, DateInterval $expires)
  • $values - 可遍历的值必须以 key => data 格式提供,并且必须是可遍历的

从缓存中获取

$cache->get(string $key, mixed $default = null)
  • $key - string 缓存键必须是有效的字符串。

  • $default - mixed 如果键不存在,则返回默认值。

$cache->getMultiple($values)
  • $values - 可遍历的值必须以 key => data 格式提供,并且必须是可遍历的

检查缓存存储中的项目

$cache->has(string $key, mixed $default = null)
  • $default - mixed 如果键不存在,则返回默认值。

从缓存存储中删除项目

$cache->delete(string $key)
$cache->deleteMultiple(traversable $keys)
  • $keys - array/traversable 要删除的键的列表。

清除缓存存储

$cache->clear()

存储适配器

以下适配器可用

  • Rs\Storage\NullStorage
  • Rs\Storage\FileStorage
  • Rs\Storage\MemcacheStorage
  • Rs\Storage\ApcStorage(不再支持)

创建新的适配器

  • 适配器必须实现 Ds\Cache\CacheStorageInterface
  • 适配器可以扩展 Ds\Cache\Storage\AbstractStorage

初始化组件

$cache = new \Ds\Cache\Cache();

NullStorage 适配器是默认使用的,上述操作与此相同

$cache = new \Ds\Cache\Cache(
    new \Ds\Cache\NullStoage()
);

更改 CacheStorage 适配器

使用 Cache::withCacheStorage 更新缓存适配器

方法是不可变的,并返回 Ds\Cache 的新实例

Memcached

Ds\Cache\Storage\MemcacheStorage(
    Memcached $memcache,
    string $server,
    int $port,
    DateInterval $ttl
)
$memcache = $cache->withCacheStorage(
    new \Ds\Cache\Storage\MemcacheStorage(
        new \Memcached(),
        'localhost',
        11211,
        new \DateInterval('P1M')
    )
)

文件存储

Ds\Cache\Storage\FileStorage(
    string $directory,
    DateInterval $ttl
)
$filestorage = $cache->withCacheStorage(
    new \Ds\Cache\Storage\FileStorage(
        __DIR__ . '/cacheDirectory',
        new \DateInterval('P1M')
    )
)

测试

使用 phpunit 执行测试套件 Tests/Cache

$ phpunit