我浏览了互联网,但没有找到太多关于如何将任何缓存库与 Slim 框架 3 一起使用的信息。
谁能帮我解决这个问题?
最佳答案
我将 symfony/cache
与 Slim 3 一起使用。您可以使用任何其他缓存库,但我给出了这个特定库的示例设置。我应该提一下,这实际上独立于 Slim 或任何其他框架。
首先你需要在你的项目中包含这个库,我推荐使用 composer。我还将包含 predis/predis
以便能够使用 Redis 适配器:
composer 需要 symfony/cache predis/predis
然后我将使用 Dependency Injection Container 来设置缓存池,使其可供其他需要使用缓存功能的对象使用:
// 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();
});
关于php - 如何在 slim 3 中使用缓存系统(memcached、redis 或任何其他),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45207970/