Using Redis with tagging in Symfony 5

Viewed 349

trying to use Redis with tagging in my Symfony 5 app but can't seem to get RedisTagAwareAdapter to work. Saving to Redis without tags works just fine like this:

use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Contracts\Cache\ItemInterface;

$client = RedisAdapter::createConnection(
    'redis://redis'
);
$cache = new RedisAdapter($client);

$key = "testkey";
$data = "hello world";

$cacheItem = $cache->getItem($key);
$cacheItem->set($data);
$cacheItem->expiresAfter(3600);
$cache->save($cacheItem);

But if I switch to using the RedisTagAwareAdapter as this suggests then nothing gets saved:

use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter;
use Symfony\Contracts\Cache\ItemInterface;

$client = RedisAdapter::createConnection(
    'redis://redis'
);
$cache = new RedisTagAwareAdapter($client);

$key = "testkey";
$data = "hello world";

$cacheItem = $cache->getItem($key);
$cacheItem->set($data);
$cacheItem->tag('greeting');
$cacheItem->expiresAfter(3600);
$cache->save($cacheItem);

the $cache->save() returns false. No other errors are thrown.

I'm using Symfony 5, Redis server version 6.2.5 and have phpredis installed. Any ideas on what I'm doing wrong? TIA

1 Answers

The solution makes everything a lot simpler :D

The CacheAdapter (from DoctrineCache2.x) makes things -although a bit weird - loads simpler.

In your case the code would look like this:

[...]
$cacheItem = $cache->get($key, function(ItemInterface $item) {
    $item->expire(3600);
    $item->tag('greeting');
    return "hello world";
});

Now I know this looks a bit counterproductive and makes hardly any sense at a first glance but here's what actually happens:

first it tries to get the item at $key and if that is not a hit, the function callback gets into action. It will create a new item, set the tagging and lifetime and it will assign the return value as the value stored at key (that is the weird part). And while it looks convoluted it's actually really smart since all the data gathering is being done ONLY if there's not cache hit for that specific key.

Related