cacheCallback(cacheKey, duration, callback[, forceRefresh])
Last updated June 11, 2009
Version: 0 | Requires: CF5 | Library: UtilityLib
Description:
Pass a unique cache key (string), duration (using createTimeSpan()), and the function whose return value you want to cache. A fourth optional boolean argument will allow you to force cache update. Returns the value of the function passed in, or the cached return value.
Return Values:
Returns a string.
Example:
<cfscript>
function currentTime(){
return "The current time is #timeformat(now())#";
}
</cfscript>
<cfoutput>#cacheCallback("my.cache.key", CreateTimeSpan(0,0,20,0), currentTime)#</cfoutput>
Parameters:
Name | Description | Required |
---|---|---|
cacheKey | Unique key used for to store the cache. | Yes |
duration | A timespan that determines the length of the cache. | Yes |
callback | The UDF to run. | Yes |
forceRefresh | If true, forces a refresh. Defaults to false. | No |
Full UDF Source:
/**
* An easy way to cache the result of any UDF.
*
* @param cacheKey Unique key used for to store the cache. (Required)
* @param duration A timespan that determines the length of the cache. (Required)
* @param callback The UDF to run. (Required)
* @param forceRefresh If true, forces a refresh. Defaults to false. (Optional)
* @return Returns a string.
* @author Adam Tuttle (j.adam.tuttle@gmail.com)
* @version 0, June 11, 2009
*/
function cacheCallback(cacheKey, duration, callback) {
var data = "";
//optional argument: forceRefresh
if (arrayLen(arguments) eq 4){arguments.forceRefresh=arguments[4];}else{arguments.forceRefresh=false;}
//clean cachekey of periods that will cause errors
arguments.cacheKey = replace(arguments.cacheKey, ".", "_", "ALL");
//ensure cache structure is setup
if (not structKeyExists(application, "CCBCache")){application.CCBCache = StructNew();}
if (not structKeyExists(application.CCBCache, arguments.cacheKey)){application.CCBCache[arguments.cacheKey] = StructNew();}
if (not structKeyExists(application.CCBCache[arguments.cacheKey], "timeout")){application.CCBCache[arguments.cacheKey].timeout = dateAdd('yyyy',-10,now());}
if (not structKeyExists(application.CCBCache[arguments.cacheKey], "data")){application.CCBCache[arguments.cacheKey].data = '';}
//update cache if expired
if (arguments.forceRefresh or dateCompare(now(), application.CCBCache[arguments.cacheKey].timeout) eq 1){
data = arguments.callback();
application.CCBCache[arguments.cacheKey].data = data;
application.CCBCache[arguments.cacheKey].timeout = arguments.duration;
}
return application.CCBCache[arguments.cacheKey].data;
}
Search CFLib.org
Latest Additions
Raymond Camden added
QueryDeleteRows
November 04, 2017
Leigh added
nullPad
May 11, 2016
Raymond Camden added
stripHTML
May 10, 2016
Kevin Cotton added
date2ExcelDate
May 05, 2016
Raymond Camden added
CapFirst
April 25, 2016