webiny / cache
Requires
- php: ^7
- webiny/config: ~1.6
- webiny/forked-jamm-memory: ~1.0
- webiny/service-manager: ~1.6
- webiny/std-lib: ~1.6
Requires (Dev)
- mybuilder/phpunit-accelerator: dev-master
- phpunit/phpunit: ~6
README
Cache
组件为您提供将不同信息存储到内存中的能力,存储时间有限。
安装组件
安装组件的最佳方式是使用 Composer。
composer require webiny/cache
要查看包的附加版本,请访问 Packagist 页面。
支持的驱动程序
缓存组件支持以下缓存驱动程序
APC
(https://php.ac.cn/manual/en/book.apc.php)- 仅适用于 PHP 5.4,从 PHP 5.5 开始不再支持 APC
Couchbase
(http://www.couchbase.com/develop/php/current)Memcache
(https://php.ac.cn/manual/en/book.memcache.php)Redis
(https://redis.ac.cn/clients)
如果您不确定要使用哪个驱动程序,我们建议使用 Memcache
。
根据所选的驱动程序,您必须向构造函数传递不同的选项。
要求
默认的桥接库是 Memory
,由 Jamm
提供 (https://github.com/jamm/Memory)。您必须将其添加到 ClassLoader
中。
\Webiny\Components\ClassLoader::getInstance()->registerMap(['Jamm\Memory' => 'path to memory lib']);
例如
// APC $cache = \Webiny\Component\Cache\Cache::APC('cache-id'); // Couchbase $cache = \Webiny\Component\Cache\Cache::Couchbase('CacheService', 'username', 'password', 'bucket', '127.0.0.1:8091'); // Memcache $cache = \Webiny\Component\Cache\Cache::Memcache('CacheService', 'localhost', 11211); // Redis $cache = \Webiny\Component\Cache\Cache::Redis('CacheService', 'localhost', 6379);
常见操作
一旦您创建了您的 Cache
实例,您就可以开始使用您的缓存。缓存方法相同,无论您使用哪个驱动程序
// write to cache $cache->save('myKey', 'some value', 600, ['tag1', 'tag2']); // read from cache $cache->read('myKey'); // delete from cache $cache->delete('myKey'); // delete by tag $cache->deleteByTag(['tag1']);
缓存配置
定义缓存驱动程序的首选方式是在您的应用程序配置文件中创建它们。
Cache: TestCache: Factory: "\Webiny\Component\Cache\Cache" Method: "Apc" SomeOtherCache: Factory: "\Webiny\Component\Cache\Cache" Method: "Memcache" Arguments: ['127.0.0.1', '11211']
请参阅 ExampleConfig.yaml
以获取更多信息。
在 Cache
下,通过为每个驱动程序提供一个 cache id
并嵌套其配置来定义缓存驱动程序。驱动程序配置取决于您使用的驱动程序。
如果您想关闭缓存,请使用 BlackHole
驱动程序。
Method
参数必须是一个有效的回调函数,该函数将返回一个 CacheStorage
实例。
以这种方式定义缓存驱动程序的好处是,当 Webiny 框架被加载时,驱动程序将初始化。这使您能够通过 'CacheTrait' 访问缓存。
class MyClass { use \Webiny\Component\Cache\CacheTrait; public function myMethod(){ $this->cache('Frontend')->read('cache_key'); } }
自定义 Cache
驱动程序
要实现您自己的自定义缓存驱动程序,您必须首先创建一个将实现 \Webiny\Component\Cache\Bridge\CacheInterface
的类。一旦有了这个类,就创建另一个类,其中包含一个静态函数,该函数将返回一个 CacheDriver
实例。
class CustomCacheDriver implements \Webiny\Component\Cache\Bridge\CacheInterface { // implement the interface methods // static method that will return the CacheDriver function getDriver($cacheId, $param1, $param2, array $options){ $driver = new static($cacheId, $param1, $param2); return \Webiny\Component\Cache\CacheDriver($driver, $options); } }
现在只需将您的类和静态方法作为配置中的 Method
设置,您就可以通过 CacheTrait
访问缓存。
资源
要运行单元测试,您需要使用以下命令
$ cd path/to/Webiny/Component/Cache/
$ composer.phar install
$ phpunit
请确保您还在 Tests/ExampleConfig.yaml
中设置了您的缓存驱动程序详细信息。