skip to Main Content

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?

2

Answers


  1. 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 PredisClient($config);
        return new SymfonyComponentCacheAdapterRedisAdapter($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();
    });
    
    Login or Signup to reply.
  2. $memcached = new Memcached();
    
    $memcached->addServer($cachedHost, $cachedPort);
    
    $metadataCache = new DoctrineCommonCacheMemcachedCache();
    $metadataCache->setMemcached($memcached);
    
    $queryCache = new DoctrineCommonCacheMemcachedCache();
    $queryCache->setMemcached($memcached);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search