Using Redis cache with Symfony

History

How to configure Redis

# run this if you are building a traditional web application
composer create-project symfony/website-skeleton my_project_name

# building a microservice, console application or API
composer create-project symfony/skeleton my_project_name
composer require symfony-bundles/redis-bundle
#projectName/config/bundles.php
SymfonyBundles\RedisBundle\SymfonyBundlesRedisBundle::class => ['all' => true],
#projectName/config/packages/sb_redis.yaml:
sb_redis:
clients:
default:
$options: []
$parameters: ['tcp://127.0.0.1:6379?database=3']

How to use

<?php

declare(strict_types=1);

namespace App\Infrastructure\Service\Redis;

use SymfonyBundles\RedisBundle\Redis\ClientInterface;

class RedisStorageManager
{
private ClientInterface $redis;

public function __construct(ClientInterface $redis)
{
$this->redis = $redis;
}
}
public function find(string $key): ?string
{
return $this->redis->get($this->getRedisKey($key));
}
private function getRedisKey(string $key): string
{
return sprintf('%s.%s', $this->prefix, $key);
}
public function set(string $key, string $value): void
{
$key = $this->getRedisKey($key);

$this->redis->set($key, $value);
$this->redis->expire($key, $this->ttl);
}
<?php

declare(strict_types=1);

namespace App\Infrastructure\Service\Redis;

use SymfonyBundles\RedisBundle\Redis\ClientInterface;

class RedisStorageManager
{
private string $prefix;
private int $ttl;
private ClientInterface $redis;

public function __construct(string $prefix, int $ttl, ClientInterface $redis)
{
$this->prefix = $prefix;
$this->ttl = $ttl;
$this->redis = $redis;
}

public function find(string $key): ?string
{
return $this->redis->get($this->getRedisKey($key));
}

public function findArrayValue(string $key): ?array
{
return $this->redis->hgetall($this->getRedisKey($key));
}

public function set(string $key, string $value): void
{
$key = $this->getRedisKey($key);

$this->redis->set($key, $value);
$this->redis->expire($key, $this->ttl);
}

public function setArray(string $key, array $value): void
{
$key = $this->getRedisKey($key);

$this->redis->hmset($key, $value);
$this->redis->expire($key, $this->ttl);
}

public function remove(string $key): void
{
$this->redis->remove($this->getRedisKey($key));
}

public function has(string $key): bool
{
return (bool) $this->find($this->getRedisKey($key));
}

private function getRedisKey(string $key): string
{
return sprintf('%s.%s', $this->prefix, $key);
}
}

Senior Software Engineer from Kyiv, in @MacPaw company.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store