123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- <?php
- namespace yii\redis;
- use Yii;
- use yii\base\InvalidConfigException;
- class Session extends \yii\web\Session
- {
-
- public $redis = 'redis';
-
- public $keyPrefix;
-
- public function init()
- {
- if (is_string($this->redis)) {
- $this->redis = Yii::$app->get($this->redis);
- } elseif (is_array($this->redis)) {
- if (!isset($this->redis['class'])) {
- $this->redis['class'] = Connection::className();
- }
- $this->redis = Yii::createObject($this->redis);
- }
- if (!$this->redis instanceof Connection) {
- throw new InvalidConfigException("Session::redis must be either a Redis connection instance or the application component ID of a Redis connection.");
- }
- if ($this->keyPrefix === null) {
- $this->keyPrefix = substr(md5(Yii::$app->id), 0, 5);
- }
- parent::init();
- }
-
- public function getUseCustomStorage()
- {
- return true;
- }
-
- public function readSession($id)
- {
- $data = $this->redis->executeCommand('GET', [$this->calculateKey($id)]);
- return $data === false || $data === null ? '' : $data;
- }
-
- public function writeSession($id, $data)
- {
- return (bool) $this->redis->executeCommand('SET', [$this->calculateKey($id), $data, 'EX', $this->getTimeout()]);
- }
-
- public function destroySession($id)
- {
- $this->redis->executeCommand('DEL', [$this->calculateKey($id)]);
-
- return true;
- }
-
- protected function calculateKey($id)
- {
- return $this->keyPrefix . md5(json_encode([__CLASS__, $id]));
- }
- }
|