Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom implementation of Sugar redis cache, using authentication and persistent connection
<?php
// Enrico Simonetti
// enricosimonetti.com
//
// 2017-11-23 tested on Sugar 7.9.2.0 on PHP 7.1 with the addition of: https://gist.github.com/esimonetti/a99ea05b68cd2586949944c1b24b2921
// Custom implementation of Sugar redis cache, using authentication if configured and using persistent connections if configured
//
// file: custom/include/SugarCache/CustomSugarCacheRedis.php
// to enable, use the following config options:
// $sugar_config['external_cache_disabled_customredis'] = false;
// $sugar_config['external_cache_disabled_redis'] = true;
// to configure auth use the following config option:
// $sugar_config['external_cache']['redis']['auth'] = '<your redis auth password>';
// to configure persistent connection use the following config option:
// $sugar_config['external_cache']['redis']['persistent'] = true;
class CustomSugarCacheRedis extends SugarCacheRedis
{
// decreased priority from 920 to 919 vs SugarCacheRedis, so that this will be used instead of SugarCacheRedis
protected $_priority = 919;
protected $_auth = '';
protected $_persistent = false;
/**
* @see SugarCacheAbstract::useBackend()
*/
public function useBackend()
{
// check grandparent, as parent would prevent it from running
if (!SugarCacheAbstract::useBackend() ) {
return false;
}
if ( extension_loaded("redis")
&& empty($GLOBALS['sugar_config']['external_cache_disabled_customredis'])
&& $this->_getRedisObject() ) {
return true;
}
return false;
}
/**
* Get the redis object; initialize if needed
*/
protected function _getRedisObject()
{
try {
if (!($this->_redis instanceOf Redis)) {
$this->_redis = new Redis();
$this->_host = SugarConfig::getInstance()->get('external_cache.redis.host', $this->_host);
$this->_port = SugarConfig::getInstance()->get('external_cache.redis.port', $this->_port);
$this->_auth = SugarConfig::getInstance()->get('external_cache.redis.auth', $this->_auth);
$this->_persistent = SugarConfig::getInstance()->get('external_cache.redis.persistent', $this->_persistent);
$method = 'connect';
if ($this->_persistent) {
$method = 'pconnect';
}
if ($this->_redis->$method($this->_host, $this->_port)) {
if (!empty($this->_auth)) {
if (!$this->_redis->auth($this->_auth)) {
return false;
}
}
} else {
return false;
}
}
}
catch (RedisException $e)
{
return false;
}
return $this->_redis;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.