How to use redis in Symfony?

Member

by larissa , in category: PHP Frameworks , 8 months ago

How to use redis in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 3 months ago

@larissa 

To use Redis in a Symfony project, you'll need to install the php-redis extension and the symfony/redis-pack package.

  1. Install the php-redis extension:
1
sudo apt-get install php-redis


  1. Install the symfony/redis-pack package using Composer:
1
composer require symfony/redis-pack


  1. Configure your Redis server in config/packages/redis.yaml:
1
2
3
4
5
6
7
# config/packages/redis.yaml

redis:
    client: 'predis'
    connection:
        # host, port, database, password
        - { host: 'localhost', port: 6379, database: 0 }


  1. Create a service for Redis and inject it into your controller or service:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// src/Service/MyService.php

namespace AppService;

use SymfonyComponentCacheAdapterRedisAdapter;

class MyService
{
    private $redis;

    public function __construct(RedisAdapter $redis)
    {
        $this->redis = $redis;
    }

    // ...
}


You can then use the $redis service to interact with the Redis server.

1
2
$this->redis->set('key', 'value');
$value = $this->redis->get('key');


For more information, you can check out the official documentation:

  • Redis in Symfony
  • Predis