cacheCallback(cacheKey, duration, callback [, forceRefresh])
Last updated June 11, 2009
Version: 0 | Requires: ColdFusion 5 | 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:
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:
<cfscript>
/**
* 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;
}
</cfscript>
Search CFLib.org
Latest Additions
Tayo Akinmade added
arrayTrim
11 day(s) ago
Will Belden added
longTime
17 day(s) ago
James Sleeman added
quickSort
27 day(s) ago
Ben Forta added
GetHostAddress
30 day(s) ago
Top Rated
EksporSQLData
Rated 5.0, 16 time(s)
backupDatabase
Rated 5.0, 13 time(s)
indentXml
Rated 5.0, 10 time(s)
generateSsccAsn
Rated 5.0, 4 time(s)