2017-07-20 111 views
1

我浏览了互联网,没有找到关于如何在slim 3框架中使用任何缓存库的内容。 任何人都可以尽快帮我解决这个问题吗?如何在slim 3框架下使用memcached或redis 3

+0

试试这个,对于超薄2:https://gist.github.com/hising/ddece8c92bcd09df83fdcf9890fc0dd3 – informer

+0

当你说'使用超薄3的缓存库'你的意思是你想添加一个缓存库到你的应用程序,然后从框架中获得帮助?我在我的超薄3应用程序中使用缓存,但我在任何我认为合适的地方手动使用它,而不是从纤细的特殊处理。我的意思是我自己生成独特的缓存密钥,检查项目是否在池中等。如果您提供更多信息,我可以提供帮助。 – Nima

+0

从@ @ima(首次使用缓存)获取有关在项目中使用缓存的信息将会很棒。如何使用或不使用任何库的缓存? – Ayush28

回答

5

我使用symfony/cache与Slim 3.您可以使用任何其他缓存库,但我给出了这个特定库的示例设置。我应该提到,这实际上与Slim或其他任何框架无关。

首先,您需要将此库包含在您的项目中,我推荐使用作曲家。我也将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(); 
});