2014-07-19 15:37:48 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
2014-07-21 15:12:51 +02:00
|
|
|
namespace Addr\Cache;
|
2014-07-19 15:37:48 +02:00
|
|
|
|
2014-07-21 15:12:51 +02:00
|
|
|
use Addr\Cache;
|
2014-07-19 15:37:48 +02:00
|
|
|
use Predis\Client as RedisClient;
|
|
|
|
|
2014-07-21 15:12:51 +02:00
|
|
|
|
|
|
|
class RedisCache implements Cache {
|
2014-07-19 15:37:48 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @var RedisClient
|
|
|
|
*/
|
|
|
|
private $redisClient;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Lua script to get a value, and flag whether it was cache hit or miss.
|
|
|
|
* Don't delete the "== 1" - it's important in Lua
|
|
|
|
*/
|
|
|
|
const getLuaScript = <<< END
|
|
|
|
if redis.call("exists", KEYS[1]) == 1
|
|
|
|
then
|
|
|
|
return {1, redis.call("get",KEYS[1])}
|
|
|
|
else
|
|
|
|
return {0, 0}
|
|
|
|
end
|
|
|
|
|
|
|
|
END;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param RedisClient $redisClient
|
|
|
|
* @param string $prefixKey A prefix to prepend to all keys. This can also be
|
|
|
|
* set via the redis client, in which case you may wish to pass an empty string
|
|
|
|
* as $prefixKey
|
|
|
|
*/
|
2014-07-21 15:12:51 +02:00
|
|
|
function __construct(RedisClient $redisClient, $prefixKey = 'AddrCache\Cache\RedisCache')
|
|
|
|
{
|
2014-07-19 15:37:48 +02:00
|
|
|
$this->redisClient = $redisClient;
|
|
|
|
$this->prefix = $prefixKey;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Stores a value in the cache. Overwrites the previous value if there was one.
|
|
|
|
*
|
|
|
|
* @param $key
|
|
|
|
* @param $value
|
|
|
|
* @param null $ttl
|
|
|
|
*/
|
2014-07-21 15:12:51 +02:00
|
|
|
public function store($key, $value, $ttl = null)
|
|
|
|
{
|
2014-07-19 15:37:48 +02:00
|
|
|
$key = $this->prefix.$key;
|
|
|
|
$ttl = intval($ttl);
|
|
|
|
if ($ttl > 0) {
|
|
|
|
$this->redisClient->set($key, $value, 'EX', $ttl);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
$this->redisClient->set($key, $value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Attempt to retrieve a value from the cache
|
|
|
|
*
|
|
|
|
* Returns an array [$cacheHit, $value]
|
|
|
|
* [true, $valueFromCache] - if it existed in the cache
|
|
|
|
* [false, null] - if it didn't already exist in the cache
|
|
|
|
*
|
|
|
|
* @param $key
|
|
|
|
* @return array
|
|
|
|
*/
|
2014-07-21 15:12:51 +02:00
|
|
|
public function get($key)
|
|
|
|
{
|
2014-07-19 15:37:48 +02:00
|
|
|
$key = $this->prefix.$key;
|
|
|
|
list($wasHit, $value) = $this->redisClient->eval(self::getLuaScript, 1, $key);
|
|
|
|
if ($wasHit) {
|
|
|
|
return [true, $value];
|
|
|
|
}
|
|
|
|
|
|
|
|
return [false, null];
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param $key
|
|
|
|
*/
|
2014-07-21 15:12:51 +02:00
|
|
|
public function delete($key)
|
|
|
|
{
|
2014-07-19 15:37:48 +02:00
|
|
|
$key = $this->prefix.$key;
|
|
|
|
$this->redisClient->del([$key]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|