Ayush28
Ayush28

Reputation: 379

How to use a caching system (memcached, redis or any other) with slim 3

I browsed the internet and didn't find much information on how to use any caching library with Slim framework 3.

Can anyone help me with this issue?

Upvotes: 1

Views: 5344

Answers (2)

dnita
dnita

Reputation: 1

$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);

Upvotes: 0

Nima
Nima

Reputation: 3409

I use symfony/cache with Slim 3. You can use any other cache library, but I give an example setup for this specific library. And I should mention, this is actually independent of Slim or any other framework.

First you need to include this library in your project, I recommend using composer. I also will iinclude predis/predis to be able to use Redis adapter:

composer require symfony/cache predis/predis

Then I'll use Dependency Injection Container to setup cache pool to make it available to other objects which need to use caching features:

// 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);
}

Now you have a cache item pool in $container['cache'] which has methods defined in PSR-6.

Here is a sample code using it:

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.';
        }
    }
}

Now when you want to create new instance of SampleClass you should pass this cache item pool from the DIC, for example in a route callback:

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

Upvotes: 9

Related Questions