Skip to content

Instantly share code, notes, and snippets.

@ethaizone
Last active March 11, 2016 10:15
Show Gist options
  • Save ethaizone/3befa8aed0b4174de62c to your computer and use it in GitHub Desktop.
Save ethaizone/3befa8aed0b4174de62c to your computer and use it in GitHub Desktop.
<?php
use Redis;
use Exception;
/**
* Redis cache - Port from Phalcon Cache
* Cut intergate from backend and front cache
* I don't test or try run it. This pass on php linter.
* When I want to use it, I will check later.
* Welcome any fix.
*
* Port by Nimit Suwannagate <[email protected]>
*/
class RedisCache
{
protected $_redis = null;
protected $_options = null;
protected $_prefix = "";
/**
* RedisLoggerAdapter constructor
*
* @param array options
*/
public function __construct($options = null)
{
if ($options != "array") {
$options = [];
}
$this->_options = $options;
if (!isset($this->_options["host"])) {
$this->_options["host"] = "127.0.0.1";
}
if (!isset($this->_options["port"])) {
$this->_options["port"] = 6379;
}
if (!isset($this->_options["index"])) {
$this->_options["index"] = 0;
}
if (!isset($this->_options["persistent"])) {
$this->_options["persistent"] = false;
}
if (!isset($this->_options["statsKey"]) || empty($this->_options["statsKey"])) {
$this->_options["statsKey"] = "_RDC";
}
if (!empty($this->_options["prefix"])) {
$this->_prefix = $this->_options["prefix"];
}
}
/**
* Create internal connection to redis
*/
public function _connect()
{
$this->_options = $this->_options;
$redis = new Redis();
if (!empty($this->_options["host"]) && !empty($this->_options["port"]) && !empty($this->_options["persistent"])){
throw new Exception("Unexpected inconsistency in options");
}
if ($this->_options["persistent"]) {
$success = $redis->pconnect($this->_options["host"], $this->_options["port"]);
} else {
$success = $redis->connect($this->_options["host"], $this->_options["port"]);
}
if (!$success) {
throw new Exception("Could not connect to the Redisd server ".$this->_options["host"].":".$this->_options["port"]);
}
if (!empty($this->_options["auth"])){
$success = $redis->auth($this->_options["auth"]);
if (!$success) {
throw new Exception("Failed to authenticate with the Redisd server");
}
}
if (!empty($this->_options["index"])){
$success = $redis->select($this->_options["index"]);
if (!$success) {
throw new Exception("Redisd server selected database failed");
}
}
$this->_redis = $redis;
}
protected function _prepareKey($keyName)
{
if (!isset($this->_options["statsKey"])) {
throw new Exception("Unexpected inconsistency in options");
}
return $this->options["statsKey"] . $this->_prefix . $keyName;
}
/**
* Returns a cached content
*
* @param int|string keyName
* @param long lifetime
* @return mixed
*/
public function get($keyName, $lifetime = null)
{
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
$lastKey = $this->_prepareKey($keyName);
$cachedContent = $this->_redis->get($lastKey);
if (! $cachedContent) {
return null;
}
return json_decode($cachedContent, true);
}
/**
* Stores cached content into the file backend and stops the frontend
*
* @param int|string keyName
* @param string content
* @param long lifetime
*/
public function save($keyName, $content, $lifetime = null)
{
if (!isset($this->_options["statsKey"])) {
throw new Exception("Unexpected inconsistency in options");
}
$lastKey = $this->_prepareKey($keyName);
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
$success = $this->_redis->set($lastKey, json_encode($content));
if (!$success) {
throw new Exception("Failed storing the data in redis");
}
if ($lifetime) {
$this->_redis->settimeout($lastKey, $lifetime);
}
// add last key for list purge
$this->_redis->sAdd($this->_options["statsKey"], $lastKey);
return true;
}
/**
* Deletes a value from the cache by its key
*
* @param int|string keyName
* @return boolean
*/
public function delete($keyName)
{
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
if (!isset($this->_options["statsKey"])) {
throw new Exception("Unexpected inconsistency in options");
}
$lastKey = $this->_prepareKey($keyName);
$this->_redis->sRem($this->_options["statsKey"], $lastKey);
/**
* Delete the key from redis
*/
return $this->_redis->delete($lastKey);
}
/**
* Query the existing cached keys
*
* @return array
*/
public function queryKeys($prefix = null)
{
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
if (!isset($this->_options["statsKey"])) {
throw new Exception("Unexpected inconsistency in options");
}
/**
* Get the key from redis
*/
$keys = $this->_redis->sMembers($this->_options["statsKey"]);
if (is_array($keys)) {
foreach ($keys as $key => $value) {
if ($prefix && !strpos($value, $prefix) === 0) {
unset($keys[$key]);
}
}
}
return $keys;
}
/**
* Checks if cache exists and it isn't expired
*
* @param string keyName
* @return boolean
*/
public function exists($keyName)
{
$lastKey = $this->_prepareKey($keyName);
if ($lastKey) {
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
if (!$this->_redis->get($lastKey)) {
return false;
}
return true;
}
return false;
}
/**
* Increment of given $keyName by $value
*
* @param string keyName
* @param long value
* @return long
*/
public function increment($keyName, $value = null)
{
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
$lastKey = $this->_prepareKey($keyName);
if (!$value) {
$value = 1;
}
return $this->_redis->incrBy($lastKey, $value);
}
/**
* Decrement of $keyName by given $value
*
* @param string keyName
* @param long value
* @return long
*/
public function decrement($keyName, $value = null)
{
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
$lastKey = $this->_prepareKey($keyName);
if (!$value) {
$value = 1;
}
return $this->_redis->decrBy($lastKey, $value);
}
/**
* Immediately invalidates all existing items.
*/
public function flush()
{
/**
* Check if a connection is created or make a new one
*/
if (!is_object($this->_redis)) {
$this->_connect();
}
if (!isset($this->_options["statsKey"])) {
throw new Exception("Unexpected inconsistency in options");
}
$keys = $this->_redis->sMembers($this->_options["statsKey"]);
if (is_array($keys)) {
foreach ($keys as $key) {
$this->_redis->sRem($this->_options["statsKey"], $key);
$this->_redis->delete($key);
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment