如何使用苗条3的memcached或redis

Ayu*_*h28 1 php memcached redis slim-3

我浏览了互联网,并没有找到关于如何使用苗条3框架的任何缓存库的内容.一旦有人能帮我解决这个问题吗?

Nim*_*ima 8

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

首先,您需要在项目中包含此库,我建议使用composer.我也将包括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);
}
Run Code Online (Sandbox Code Playgroud)

现在您有一个缓存项池,$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.';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当您想要创建SampleClass的新实例时,您应该从DIC传递此缓存项池,例如在路由回调中:

$app->get('/foo', function (){
    $bar = new SampleClass($this->get('cache'));
    return $bar->doSomething();
});
Run Code Online (Sandbox Code Playgroud)