Skip to content

Instantly share code, notes, and snippets.

@esimonetti
Last active November 13, 2019 00:10
Show Gist options
  • Save esimonetti/dd7b268ff8e2e551e2f4b5dac19d4e82 to your computer and use it in GitHub Desktop.
Save esimonetti/dd7b268ff8e2e551e2f4b5dac19d4e82 to your computer and use it in GitHub Desktop.
With the new PSR-16 compatible caching engine we introduced recently, the new way to get the caching object is with something like this sample code
<?php
// remember to set redis on config_override.php
/*
$sugar_config['external_cache_disabled'] = false;
$sugar_config['external_cache_disabled_redis'] = false;
$sugar_config['external_cache']['redis']['host'] = 'sugar-redis';
*/
// to test the simplest standalone script
/*
define('sugarEntry', true);
require_once('include/entryPoint.php');
$GLOBALS['current_user'] = BeanFactory::newBean('Users')->getSystemUser();
*/
use Sugarcrm\Sugarcrm\DependencyInjection\Container;
use Psr\SimpleCache\CacheInterface;
$cache = Container::getInstance()->get(CacheInterface::class);
$cacheVariableKey = 'unique_cache_key';
$optionalTTL = 30;
$storedVariable = $cache->get($cacheVariableKey);
// return cached info
if (isset($storedVariable)) {
$decodedStoredVariable = json_decode(base64_decode($storedVariable), true);
$GLOBALS['log']->fatal('returning value of key ' . $cacheVariableKey . ' from cache ' . print_r($decodedStoredVariable, true));
return $decodedStoredVariable;
} else {
// retrieve the actual live data here
$data = ['a', 'b', 'c'];
$GLOBALS['log']->fatal('retrieving live data and storing it into ' . $cacheVariableKey);
// store retrieved data in cache and return
$cache->set($cacheVariableKey, base64_encode(json_encode($data)), $optionalTTL);
return $data;
}
// to delete previously cached data use
//$cache->delete($cacheVariableKey);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment