Skip to content

Instantly share code, notes, and snippets.

@jancbeck
Created October 2, 2015 16:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jancbeck/83acdfe8dd0e92fe2c56 to your computer and use it in GitHub Desktop.
Save jancbeck/83acdfe8dd0e92fe2c56 to your computer and use it in GitHub Desktop.
Redis Cache for Kirby. Requires Predis.
<?php
namespace Cache\Driver;
use Cache\Driver;
/**
* Redis
*
* @package Kirby Redis
* @author Jan Beck <mail@jancbeck.com>
* @link http://jancbeck.com
* @copyright Jan Beck
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Redis extends Driver {
// store for the redis connection
protected $connection = null;
/**
* Set all parameters which are needed for the redis client
* see defaults for available parameters
*
* @param array $params
* @return void
*/
public function __construct($params = array()) {
$defaults = array(
'host' => 'localhost',
'port' => 11211,
'prefix' => null,
'scheme' => 'tcp'
);
$this->options = array_merge($defaults, (array)$params);
$this->connection = new Predis\Client($this->options);
}
/**
* Write an item to the cache for a given number of minutes.
*
* <code>
* // Put an item in the cache for 15 minutes
* Cache::set('value', 'my value', 15);
* </code>
*
* @param string $key
* @param mixed $value
* @param int $minutes
* @return void
*/
public function set($key, $value, $minutes = null) {
if ( $minutes ) {
return $this->connection->setex($this->key($key), $this->expiration($minutes), $this->value($value));
} else {
return $this->connection->set($this->key($key), $this->value($value));
}
}
/**
* Returns the full keyname
* including the prefix (if set)
*
* @param string $key
* @return string
*/
public function key($key) {
return $this->options['prefix'] . $key;
}
/**
* Retrieve the CacheValue object from the cache.
*
* @param string $key
* @return object CacheValue
*/
public function retrieve($key) {
return $this->connection->get($this->key($key));
}
/**
* Remove an item from the cache
*
* @param string $key
* @return boolean
*/
public function remove($key) {
return $this->connection->del($this->key($key));
}
/**
* Checks when an item in the cache expires
*
* @param string $key
* @return int
*/
public function expires($key) {
return parent::expires($this->key($key));
}
/**
* Checks if an item in the cache is expired
*
* @param string $key
* @return int
*/
public function expired($key) {
return parent::expired($this->key($key));
}
/**
* Checks when the cache has been created
*
* @param string $key
* @return int
*/
public function created($key) {
return parent::created($this->key($key));
}
/**
* Flush the entire cache directory
*
* @return boolean
*/
public function flush() {
return $this->connection->flushdb();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment