【问题标题】:How to use a caching system (memcached, redis or any other) with slim 3如何在 slim 3 中使用缓存系统(memcached、redis 或任何其他)
【发布时间】:2017-12-25 18:04:15
【问题描述】:

我浏览了互联网,并没有找到太多关于如何在 Slim 框架 3 中使用任何缓存库的信息。

谁能帮我解决这个问题?

【问题讨论】:

  • 当您说use a caching library with slim 3 时,您的意思是您想为您的应用程序添加一个缓存库,然后从框架中获得帮助?我在我的 slim 3 应用程序中使用缓存,但我在任何我认为合适的地方手动使用它,slim 没有特殊处理。我的意思是我自己生成唯一的缓存键,检查项目是否在池中,等等。如果您提供更多信息,我可以提供帮助。
  • 如果你能从@Nima 那里获得一些关于在项目中使用缓存的信息(第一次使用缓存),那就太好了。如何在有或没有任何库的情况下使用缓存?
  • 你能指导我如何手动使用缓存@Nima

标签: php redis memcached slim-3


【解决方案1】:

我将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();
});

【讨论】:

    【解决方案2】:
    $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);
    

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 2017-08-06
      • 1970-01-01
      • 2011-06-26
      相关资源
      最近更新 更多