2 Answers

9
votes

You need to define 2 services:

  • One for the Redis connection.
  • One for RedisSessionHandler that will make use of that connection.

Edit the services file:

# config/services.yaml
services:
    Redis:
        class: Redis
        calls:
            - method: connect
              arguments:
                  - '%env(REDIS_HOST)%'
                  - '%env(int:REDIS_PORT)%'
            # If you need key prefix
            # - method: setOption
            #   arguments:
            #       - !php/const Redis::OPT_PREFIX
            #       - 'my_prefix'

    Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler:
        arguments:
            - '@Redis'

(note that I stored here the Redis host & port as environment variables, but you can define them elsewhere if needed).

You can now make use of the service as your session handler:

# config/packages/framework.yaml
framework:  
    session:
        handler_id: Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler

I struggled a bit too, and wrote a more detailed articled: http://blog.michaelperrin.fr/2018/08/14/redis-session-handling-in-symfony/

2
votes

For adding custom prefix, maybe the following is better:

    Redis:
        class: Redis
        calls:
            - method: connect
              arguments:
                  - '%env(REDIS_HOST)%'
                  - '%env(int:REDIS_PORT)%'

#            - method: setOption
#              arguments:
#                  # @see https://symfony.com/blog/new-in-symfony-3-2-php-constants-in-yaml-files
#                  - !php/const Redis::OPT_PREFIX

    Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler:
        arguments:
            - '@Redis'
            # @see https://symfony.com/doc/current/components/yaml/yaml_format.html
            -
                prefix: ivannotes_