ds / cache
v1.0.0
2017-11-27 15:20 UTC
Requires
- psr/simple-cache: 1.0.0
Requires (Dev)
- codeclimate/php-test-reporter: dev-master
- phpunit/phpunit: 5.3.*
This package is not auto-updated.
Last update: 2018-06-13 16:22:31 UTC
README
Ds\Cache - PSR 16 简单缓存实现
psr/simple-cache 了解更多关于 PSR-16 的信息。
安装
使用 Composer 安装组件
$ composer require ds/cache "^v2.0.*"
使用
保存到缓存
$cache->set(string $key, mixed $value, DateInterval|int|null $expires)
-
$key- string 缓存键必须是有效的字符串。 -
$value- mixed 要存储在缓存中的数据 -
$expires- DateInterval|int|null 如果为 null,则使用默认过期时间。
$cache->setMultiple($values, DateInterval|int|null $expires)
$values- 可遍历值必须以键 => 数据格式提供,并且必须是可遍历的
从缓存中检索
$cache->get(string $key, mixed $default = null)
-
$key- string 缓存键必须是有效的字符串。 -
$default- mixed 当键不存在时返回的默认值。
$cache->getMultiple($values)
$values- 可遍历值必须以键 => 数据格式提供,并且必须是可遍历的
检查缓存存储中的项
$cache->has(string $key, mixed $default = null)
$default- mixed 当键不存在时返回的默认值。
从缓存存储中删除项
$cache->delete(string $key)
$cache->deleteMultiple(traversable $keys)
$keys- array/traversable 要删除的键列表。
清除缓存存储
$cache->clear()
存储适配器
以下适配器可用
Ds\Storage\NullStorageDs\Storage\FileStorageDs\Storage\MemcacheStorageDs\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