PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 12, 2022

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

 November 12, 2022     memcached, php, redis, slim-3     No comments   

Issue

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?


Solution

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


Answered By - Nima
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing