104corp / cache
PSR-16 简单缓存实现,由 PHP 编写。
1.0.0
2017-08-03 15:28 UTC
Requires
- php: >=5.5
- psr/simple-cache: ^1.0
Requires (Dev)
- phpunit/phpunit: <6
- squizlabs/php_codesniffer: ^3.0
This package is not auto-updated.
Last update: 2024-09-20 06:59:58 UTC
README
PSR-16 简单缓存实现,由 PHP 编写。
系统需求
- PHP >= 5.5
安装
使用 Composer 进行安装
$ composer require 104corp/cache
说明
Cache 实现遵循 PSR-16 Simple Cache 标准,并提供 CacheAwareTrait
,方便将其挂载在需要缓存功能的组件上;提供几种常见实现,可直接使用。
由于实现遵循 PSR-16 标准,如果觉得不够用,也可以直接无缝切换到第三方库。
基本
如果需要进行缓存,首先挂上 CacheAwareTrait
,并实现必要的方法 getDefaultTtl()
,然后就可以开始使用了。下面是一个简单的示例:
use Corp104\Cache\Util\CacheAwareTrait; class Resource { use CacheAwareTrait; public function getDefaultTtl() { // 60 second return 60; } public function getData() { $data = null; if (null !== $this->cache) { $data = $this->cache->get('some-resource-key', null); } if (null === $data) { $data = $this->getRealData(); if (null !== $this->cache) { $this->cache->set('some-resource-key', $data, $this->getTtl()); } } return $data; } private function getRealData() { return 'RealData'; } }
实际使用 Resource
对象时,只需传入适当的 cache driver 即可运行,如 Symfony Cache。
$cacheInstance = new \Symfony\Component\Cache\Simple\PhpFilesCache(); $resource = new Resource(); $resource->setCache($cacheInstance); $data = $resource->getData();
实现
Corp104\Cache\FileCache
- 使用 PHP 文件作为缓存。
测试替身
Cache 组件实现 Psr\SimpleCache\CacheInterface
,因此可以直接使用此接口生成 Stub / Spy / Mock。
测试阶段可以使用 Corp104\Cache\ArrayCache
来测试组件与 Cache 的交互和结果是否正常。
贡献
开发相关信息可以参考 CONTRIBUTING,有任何问题或建议,欢迎提交 issue;如果觉得代码可以改进,也欢迎提交 PR 修正。
关于如何使用 PR 的信息可以参考 Git 官方文档。