Commit a8ff62e7 authored by mikeytown2's avatar mikeytown2

Issue #2562143 by mikeytown2: Add in the ability to cache function calls and...

Issue #2562143 by mikeytown2: Add in the ability to cache function calls and regenerate cache in the background.
parent 0c6e226c
......@@ -3532,3 +3532,63 @@ function httprl_call_user_func_array_async($callback, array $param_arr) {
httprl_send_request();
}
}
/**
* Cache a function; regenerate return value in the background.
*
* @param callable $callback
* The callable to be called.
* @param array $param_arr
* The parameters to be passed to the callback, as an indexed array.
* @param array $options
* An associative array with the keys cache_lifetime_min, cache_lifetime_max,
* and bin.
*
* @return mixed
* Array of results.
*/
function httprl_call_user_func_array_cache($callback, array $param_arr = array(), array $options = array()) {
$options += array(
// How long to wait until regenerating this cached value.
'cache_lifetime_min' => 0,
// How long the cache can still be used; 3600 = 1 hour.
'cache_lifetime_max' => 3600,
// What cache bin to use.
'bin' => 'cache',
// Lock timeout.
'lock_timeout' => 30.0,
);
// The cache id for this call.
$cid = __FUNCTION__ . ':' . drupal_base64_encode(serialize(array($callback, $param_arr)));
$cache = cache_get($cid);
// Don't use the cache if it's not there or the cached item is older than
// the max cache lifetime.
if (!isset($cache->data) || $cache->created < REQUEST_TIME - $options['cache_lifetime_max']) {
$cache = new stdClass();
// Run the callback.
$cache->data = call_user_func_array($callback, $param_arr);
// Save the cached data.
cache_set($cid, $cache->data, $options['bin'], $options['cache_lifetime_max'] + time());
// Release the lock if the cache lifetime is 0.
if ($options['cache_lifetime_max'] == 0) {
httprl_lock_release($cid);
}
}
else {
// Regenerate if cache is older than min cache lifetime and no one else is
// doing the same thing.
if ( $cache->created < REQUEST_TIME - $options['cache_lifetime_min']
&& httprl_acquire_headless_lock($cid, $options['lock_timeout'])
) {
// Get all function arguments.
$args = func_get_args();
// Set max to zero so this gets regenerated in the background.
$args[2]['cache_lifetime_max'] = 0;
// Call this function again in another process with max lifetime set to
// zero.
httprl_call_user_func_array_async(__FUNCTION__, $args);
}
}
return $cache->data;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment