1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Symfony3系でセッションの保持にRedisを使う

Last updated at Posted at 2019-04-09

様々なセッションのハンドラ

Symfony3ではデフォルトでファイルにセッションを保存する仕組みになっていて、NativeFileSessionHandlerというクラスが使われます。
他にも様々なセッション用のハンドラが組み込まれており、MongoDBをセッションに使用するMongoDbSessionHandlerや、Memcacheを使用するMemcacheSessionHandlerなどがあります。

しかし...

Redisのハンドラがない

Redisのハンドラは組み込まれていません。MemcacheはあるのにRedisはない。なんてこったい。
ちなみにSymfony4ではRedisのハンドラは最初から組み込まれているみたいです。
開発をするパッケージの都合上、Symfony3でなければならず、それでもRedisを使いたい。そんな場合もあるかと思います。

Redisセッションハンドラを実装する

こちらのサイトを参考に実装しました。
サイトはSymfony2ベースでの解説ですが、ほとんど変わりません。

環境

php: 7.2
Symfony: 3.4

ハンドラーの実装

NativeSessionHandler.php
<?php

namespace App\Common;

use \Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler;

class NativeRedisSessionHandler extends NativeSessionHandler
{
    /**
    * Constructor.
    *
    * @param string $savePath Path of redis server.
    */
    public function __construct($savePath = "", $maxlifetime = 432000)
    {
        if (!extension_loaded('redis')) {
            throw new \RuntimeException('PHP does not have "redis" session module registered');
        }

        if ("" === $savePath) {
            $savePath = ini_get('session.save_path');
        }

        if ("" === $savePath) {
            $savePath = "tcp://localhost:6379"; // guess path
        }

        ini_set('session.save_handler', 'redis');
        ini_set('session.save_path', $savePath);
        ini_set('session.gc_maxlifetime', $maxlifetime);
    }
}

yamlの実装

framesorkの記述があるyamlにセッションハンドラの指定をします。

framework.yaml
services:
  session_handler_redis:
    class: App\Common\NativeRedisSessionHandler
    arguments: ['%session_redis_path%', '%session_redis_max_lifetime%']

framework:
  session:
    handler_id: session_handler_redis

parameters:
  session_redis_path: 'tcp://localhost:6379'
  session_redis_max_lifetime: 432000

追加パッケージ

上記のハンドラを使うにあたって、phpからRedisを扱うためにphp用のパッケージを入れる必要があります。
上記実装に伴ってphpredisを使いました。
dockerのphpイメージだと下記のコマンドでインストールできます。

RUN git clone -b 4.3.0 https://github.com/phpredis/phpredis.git /usr/src/php/ext/redis 
RUN docker-php-ext-install redis

これでSymfony3からRedisを使用することができます!

最後に

よきSymfony Lifeを!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?