我浏览了互联网,没有找到太多关于如何在Slim framework 3中使用缓存库的信息。
有人能帮我解决这个问题吗?
发布于 2017-07-20 23:42:34
我使用的是symfony/cache和Slim 3。你可以使用任何其他缓存库,但我给出了这个特定库的设置示例。我应该提一下,这实际上是独立于Slim或任何其他框架的。
首先你需要在你的项目中包含这个库,我推荐使用composer。我还将包含能够使用Redis适配器的predis/predis:
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();
});发布于 2018-11-21 23:12:18
$memcached = new \Memcached();
$memcached->addServer($cachedHost, $cachedPort);
$metadataCache = new \Doctrine\Common\Cache\MemcachedCache();
$metadataCache->setMemcached($memcached);
$queryCache = new \Doctrine\Common\Cache\MemcachedCache();
$queryCache->setMemcached($memcached);https://stackoverflow.com/questions/45207970
复制相似问题