我将symfony/cache 与 Slim 3 一起使用。您可以使用任何其他缓存库,但我给出了这个特定库的示例设置。我应该提一下,这实际上是独立于 Slim 或任何其他框架的。
首先你需要在你的项目中包含这个库,我推荐使用composer。我还将 iinclude predis/predis 以便能够使用 Redis 适配器:
composer require symfony/cache predis/predis
然后我将使用依赖注入容器来设置缓存池,使其可供其他需要使用缓存功能的对象使用:
// If you created your project using slim skeleton app
// this should probably be placed in depndencies.php
$container['cache'] = function ($c) {
$config = [
'schema' => 'tcp',
'host' => 'localhost',
'port' => 6379,
// other options
];
$connection = new Predis\Client($config);
return new Symfony\Component\Cache\Adapter\RedisAdapter($connection);
}
现在您在 $container['cache'] 中有一个缓存项池,其中包含 PSR-6 中定义的方法。
这是一个使用它的示例代码:
class SampleClass {
protected $cache;
public function __construct($cache) {
$this->cache = $cache;
}
public function doSomething() {
$item = $this->cache->getItem('unique-cache-key');
if ($item->isHit()) {
return 'I was previously called at ' . $item->get();
}
else {
$item->set(time());
$item->expiresAfter(3600);
$this->cache->save($item);
return 'I am being called for the first time, I will return results from cache for the next 3600 seconds.';
}
}
}
现在,当您想要创建 SampleClass 的新实例时,您应该从 DIC 传递此缓存项池,例如在路由回调中:
$app->get('/foo', function (){
$bar = new SampleClass($this->get('cache'));
return $bar->doSomething();
});