Session.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. <?php
  2. namespace dcb9\redis;
  3. use yii\base\InvalidConfigException;
  4. use Yii;
  5. /**
  6. * Redis Session implements a session component using [redis](http://redis.io/) as the storage medium.
  7. *
  8. * Redis Session requires redis version 2.6.12 or higher to work properly.
  9. *
  10. * It needs to be configured with a redis [[Connection]] that is also configured as an application component.
  11. * By default it will use the `redis` application component.
  12. *
  13. * To use redis Session as the session application component, configure the application as follows,
  14. *
  15. * ~~~
  16. * [
  17. * 'components' => [
  18. * 'session' => [
  19. * 'class' => 'dcb9\redis\Session',
  20. * 'redis' => [
  21. * 'hostname' => 'localhost',
  22. * 'port' => 6379,
  23. * 'database' => 0,
  24. * ]
  25. * ],
  26. * ],
  27. * ]
  28. * ~~~
  29. *
  30. * Or if you have configured the redis [[Connection]] as an application component, the following is sufficient:
  31. *
  32. * ~~~
  33. * [
  34. * 'components' => [
  35. * 'session' => [
  36. * 'class' => 'dcb9\redis\Session',
  37. * // 'redis' => 'redis' // id of the connection application component
  38. * ],
  39. * ],
  40. * ]
  41. * ~~~
  42. *
  43. * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only.
  44. *
  45. * @author Bob chengbin <bob@phpor.me>
  46. */
  47. class Session extends \yii\web\Session
  48. {
  49. /**
  50. * @var Connection|string|array the Redis [[Connection]] object or the application component ID of the Redis [[Connection]].
  51. * This can also be an array that is used to create a redis [[Connection]] instance in case you do not want do configure
  52. * redis connection as an application component.
  53. * After the Session object is created, if you want to change this property, you should only assign it
  54. * with a Redis [[Connection]] object.
  55. */
  56. public $redis = 'redis';
  57. /**
  58. * @var string a string prefixed to every cache key so that it is unique. If not set,
  59. * it will use a prefix generated from [[Application::id]]. You may set this property to be an empty string
  60. * if you don't want to use key prefix. It is recommended that you explicitly set this property to some
  61. * static value if the cached data needs to be shared among multiple applications.
  62. */
  63. public $keyPrefix;
  64. /**
  65. * Initializes the redis Session component.
  66. * This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
  67. * @throws InvalidConfigException if [[redis]] is invalid.
  68. */
  69. public function init()
  70. {
  71. if (is_string($this->redis)) {
  72. $this->redis = Yii::$app->get($this->redis);
  73. } elseif (is_array($this->redis)) {
  74. if (!isset($this->redis['class'])) {
  75. $this->redis['class'] = Connection::className();
  76. }
  77. $this->redis = Yii::createObject($this->redis);
  78. }
  79. if (!$this->redis instanceof Connection) {
  80. throw new InvalidConfigException("Session::redis must be either a Redis connection instance or the application component ID of a Redis connection.");
  81. }
  82. if ($this->keyPrefix === null) {
  83. $this->keyPrefix = substr(md5(Yii::$app->id), 0, 5);
  84. }
  85. $this->redis->open();
  86. parent::init();
  87. }
  88. /**
  89. * Returns a value indicating whether to use custom session storage.
  90. * This method overrides the parent implementation and always returns true.
  91. * @return boolean whether to use custom storage.
  92. */
  93. public function getUseCustomStorage()
  94. {
  95. return true;
  96. }
  97. /**
  98. * Session read handler.
  99. * Do not call this method directly.
  100. * @param string $id session ID
  101. * @return string the session data
  102. */
  103. public function readSession($id)
  104. {
  105. $data = $this->redis->get($this->calculateKey($id));
  106. return $data === false || $data === null ? '' : $data;
  107. }
  108. /**
  109. * Session write handler.
  110. * Do not call this method directly.
  111. * @param string $id session ID
  112. * @param string $data session data
  113. * @return boolean whether session write is successful
  114. */
  115. public function writeSession($id, $data)
  116. {
  117. return (bool)$this->redis->setex($this->calculateKey($id), $this->getTimeout(), $data);
  118. }
  119. /**
  120. * Session destroy handler.
  121. * Do not call this method directly.
  122. * @param string $id session ID
  123. * @return boolean whether session is destroyed successfully
  124. */
  125. public function destroySession($id)
  126. {
  127. return (bool)$this->redis->del($this->calculateKey($id));
  128. }
  129. /**
  130. * Generates a unique key used for storing session data in cache.
  131. * @param string $id session variable name
  132. * @return string a safe cache key associated with the session variable name
  133. */
  134. protected function calculateKey($id)
  135. {
  136. return $this->keyPrefix . md5(json_encode([__CLASS__, $id]));
  137. }
  138. }