2016-02-14 23:20:10 +05:30
|
|
|
<?php
|
|
|
|
namespace common\components\redis;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
use Yii;
|
|
|
|
|
|
|
|
class Key {
|
|
|
|
|
|
|
|
protected $key;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return \yii\redis\Connection
|
|
|
|
*/
|
|
|
|
public function getRedis() {
|
2016-07-17 21:43:40 +05:30
|
|
|
return Yii::$app->redis;
|
2016-02-14 23:20:10 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function getKey() {
|
|
|
|
return $this->key;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getValue() {
|
2016-02-23 03:19:46 +05:30
|
|
|
return json_decode($this->getRedis()->get($this->key), true);
|
2016-02-14 23:20:10 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function setValue($value) {
|
|
|
|
$this->getRedis()->set($this->key, json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function delete() {
|
|
|
|
$this->getRedis()->executeCommand('DEL', [$this->key]);
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function expire($ttl) {
|
|
|
|
$this->getRedis()->executeCommand('EXPIRE', [$this->key, $ttl]);
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function buildKey(array $parts) {
|
|
|
|
$keyParts = [];
|
|
|
|
foreach($parts as $part) {
|
|
|
|
$keyParts[] = str_replace('_', ':', $part);
|
|
|
|
}
|
|
|
|
|
|
|
|
return implode(':', $keyParts);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function __construct(...$key) {
|
|
|
|
if (empty($key)) {
|
|
|
|
throw new InvalidArgumentException('You must specify at least one key.');
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->key = $this->buildKey($key);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|