Skip to content

Instantly share code, notes, and snippets.

@ivantcholakov
Created August 13, 2014 22:03
Show Gist options
  • Save ivantcholakov/e1d889793e469315ec89 to your computer and use it in GitHub Desktop.
Save ivantcholakov/e1d889793e469315ec89 to your computer and use it in GitHub Desktop.
Cache_redis.php - Array/Object Support, Approach 2. See https://github.com/EllisLab/CodeIgniter/pull/3181
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.2.4 or newer
*
* NOTICE OF LICENSE
*
* Licensed under the Open Software License version 3.0
*
* This source file is subject to the Open Software License (OSL 3.0) that is
* bundled with this package in the files license.txt / license.rst. It is
* also available through the world wide web at this URL:
* http://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to obtain it
* through the world wide web, please send an email to
* licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 3.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* CodeIgniter Redis Caching Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Core
* @author Anton Lindqvist <anton@qvister.se>
* @link
*/
class CI_Cache_redis extends CI_Driver
{
/**
* A key-suffix for distinguishing serialized values.
*/
const KEY_PREFIX_FOR_SERIALIZATION = '_ci_redis_serialized:';
/**
* Default config
*
* @static
* @var array
*/
protected static $_default_config = array(
'socket_type' => 'tcp',
'host' => '127.0.0.1',
'password' => NULL,
'port' => 6379,
'timeout' => 0
);
/**
* Redis connection
*
* @var Redis
*/
protected $_redis;
// ------------------------------------------------------------------------
/**
* Get cache
*
* @param string Cache ID
* @return mixed
*/
public function get($key)
{
$value = $this->_redis->get($key);
if ($value === FALSE)
{
$value = $this->_redis->get(self::KEY_PREFIX_FOR_SERIALIZATION.$key);
if ($value !== FALSE)
{
return unserialize($value);
}
}
return $value;
}
// ------------------------------------------------------------------------
/**
* Save cache
*
* @param string $id Cache ID
* @param mixed $data Data to save
* @param int $ttl Time to live in seconds
* @param bool $raw Whether to store the raw value (unused)
* @return bool TRUE on success, FALSE on failure
*/
public function save($id, $data, $ttl = 60, $raw = FALSE)
{
if (is_array($data) OR is_object($data))
{
$this->_redis->delete($id);
$data = serialize($data);
$id = self::KEY_PREFIX_FOR_SERIALIZATION.$id;
}
return ($ttl)
? $this->_redis->setex($id, $ttl, $data)
: $this->_redis->set($id, $data);
}
// ------------------------------------------------------------------------
/**
* Delete from cache
*
* @param string Cache key
* @return bool
*/
public function delete($key)
{
return ($this->_redis->delete($key) OR $this->_redis->delete(self::KEY_PREFIX_FOR_SERIALIZATION.$key));
}
// ------------------------------------------------------------------------
/**
* Increment a raw value
*
* @param string $id Cache ID
* @param int $offset Step/value to add
* @return mixed New value on success or FALSE on failure
*/
public function increment($id, $offset = 1)
{
if ($this->_redis->exists(self::KEY_PREFIX_FOR_SERIALIZATION.$id))
{
return FALSE;
}
return $this->_redis->incr($id, $offset);
}
// ------------------------------------------------------------------------
/**
* Decrement a raw value
*
* @param string $id Cache ID
* @param int $offset Step/value to reduce by
* @return mixed New value on success or FALSE on failure
*/
public function decrement($id, $offset = 1)
{
if ($this->_redis->exists(self::KEY_PREFIX_FOR_SERIALIZATION.$id))
{
return FALSE;
}
return $this->_redis->decr($id, $offset);
}
// ------------------------------------------------------------------------
/**
* Clean cache
*
* @return bool
* @see Redis::flushDB()
*/
public function clean()
{
return $this->_redis->flushDB();
}
// ------------------------------------------------------------------------
/**
* Get cache driver info
*
* @param string Not supported in Redis.
* Only included in order to offer a
* consistent cache API.
* @return array
* @see Redis::info()
*/
public function cache_info($type = NULL)
{
return $this->_redis->info();
}
// ------------------------------------------------------------------------
/**
* Get cache metadata
*
* @param string Cache key
* @return array
*/
public function get_metadata($key)
{
$value = $this->_redis->get($key);
if ($value === FALSE)
{
$key = self::KEY_PREFIX_FOR_SERIALIZATION.$key;
$value = $this->_redis->get($key);
if ($value === FALSE)
{
return FALSE;
}
$value = unserialize($value);
}
return array(
'expire' => time() + $this->_redis->ttl($key),
'data' => $value
);
}
// ------------------------------------------------------------------------
/**
* Check if Redis driver is supported
*
* @return bool
*/
public function is_supported()
{
if (extension_loaded('redis'))
{
return $this->_setup_redis();
}
else
{
log_message('debug', 'The Redis extension must be loaded to use Redis cache.');
return FALSE;
}
}
// ------------------------------------------------------------------------
/**
* Setup Redis config and connection
*
* Loads Redis config file if present. Will halt execution
* if a Redis connection can't be established.
*
* @return bool
* @see Redis::connect()
*/
protected function _setup_redis()
{
$config = array();
$CI =& get_instance();
if ($CI->config->load('redis', TRUE, TRUE))
{
$config += $CI->config->item('redis');
}
$config = array_merge(self::$_default_config, $config);
$this->_redis = new Redis();
try
{
if ($config['socket_type'] === 'unix')
{
$success = $this->_redis->connect($config['socket']);
}
else // tcp socket
{
$success = $this->_redis->connect($config['host'], $config['port'], $config['timeout']);
}
if ( ! $success)
{
log_message('debug', 'Cache: Redis connection refused. Check the config.');
return FALSE;
}
}
catch (RedisException $e)
{
log_message('debug', 'Cache: Redis connection refused ('.$e->getMessage().')');
return FALSE;
}
if (isset($config['password']))
{
$this->_redis->auth($config['password']);
}
return TRUE;
}
// ------------------------------------------------------------------------
/**
* Class destructor
*
* Closes the connection to Redis if present.
*
* @return void
*/
public function __destruct()
{
if ($this->_redis)
{
$this->_redis->close();
}
}
}
/* End of file Cache_redis.php */
/* Location: ./system/libraries/Cache/drivers/Cache_redis.php */
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Redis_test extends CI_Controller {
public function index() {
echo '<br />';
echo 'CodeIgniter 3.0-dev: Redis Caching Driver Test.';
echo '<br />';
echo '<br />';
echo 'phpredis version: '.@phpversion('redis');
echo '<br />';
echo '<br />';
echo '<hr />';
echo '<br />';
echo 'Making a native Redis class instance: ';
echo '<br />';
$redis = new Redis() or die('Can not load redis.');
$redis->connect('127.0.0.1');
$redis_server_info = $redis->info();
$redis_server_version = $redis_server_info['redis_version'];
echo 'Redis server version: '.$redis_server_version;
echo '<br />';
echo '<br />';
echo 'Loading CodeIgniter\'s cache with redis driver.';
echo '<br />';
echo '<br />';
$this->load->driver('cache', array('adapter' => 'redis'));
// Let us see whwther they work.
echo 'The following value should increment on every page reload.';
echo '<br />';
$this->cache->increment('test_key_1');
var_dump($this->cache->get('test_key_1'));
echo '<br />';
echo '<br />';
echo 'The following value should decrement on every page reload.';
echo '<br />';
$this->cache->decrement('test_key_2');
var_dump($this->cache->get('test_key_2'));
echo '<br />';
echo '<br />';
echo 'Saving and reading an ordinary string.';
echo '<br />';
$this->cache->save('test_key_3', '--- An ordinary string ---');
var_dump($this->cache->get('test_key_3'));
echo '<br />';
echo '<hr />';
echo '<br />';
echo 'Making an array of objects ($records variable).';
echo '<br />';
$records = json_decode('[{"id":1},{"id":2},{"id":3}]');
var_dump($records);
echo '<br />';
echo '<br />';
echo 'Saving $records within cache under "records" key.';
echo '<br />';
$this->cache->save('records', $records);
echo '<hr />';
echo '<br />';
echo 'Reading "records" and showing the result.';
echo '<br />';
$records_read = $this->cache->get('records', $records);
var_dump($records_read);
echo '<br />';
echo '<br />';
echo 'Reading metadata of "records" and showing the result.';
echo '<br />';
$records_read = $this->cache->get_metadata('records');
var_dump($records_read);
echo '<br />';
echo '<hr />';
echo '<br />';
echo 'Deleting "records" and showing the result.';
echo '<br />';
$result_delete = $this->cache->delete('records', $records);
var_dump($result_delete);
echo '<br />';
echo '<br />';
echo 'Deleting "records" again and showing the result.';
echo '<br />';
$result_delete = $this->cache->delete('records', $records);
var_dump($result_delete);
echo '<br />';
echo '<br />';
echo 'Reading deleted "records" and showing the result.';
echo '<br />';
$records_read = $this->cache->get('records', $records);
var_dump($records_read);
echo '<br />';
echo '<br />';
echo 'Reading metadata of non-existing "records" and showing the result.';
echo '<br />';
$records_read = $this->cache->get_metadata('records');
var_dump($records_read);
echo '<br />';
echo '<hr />';
echo '<br />';
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment