Ask a Jedi: Caching Results from ColdFusion Tags

Jared asks:

Ray, What is a good way to cache results from CFDIRECTORY LIST? The issue is I'm populating a cftree with results from a cfdirectory and want to cache the results. [Lots of files and dirs] I've been messing around with Ben Forta's example for populating the cftree and wanted to add some caching. What would you suggest?

The simplest way is to use ColdFusion’s built-in persistant scopes! All you need to do is store the result of the cfdirectory call in the Application scope. Here is an example (and let me warn you, I haven’t had my first full cup of coffee yet, so watch out for typos):

<cfif not isDefined("application.dirlisting")>
<cfdirectory directory="c:\media\mp3s\" recurse="yes" name="application.dirlisting">
</cfif>

The code above simply says, if there is no variable in the application scope called dirlisting, run the cfdirectory tag and store the result in the application scope. Note the use of recurse=yes, a new feature in ColdFusion MX 7. (To be precise, you should know that if two or more people hit this page at the exact same time, it is possible they can both run the cfdirectory tag. Since this doesn’t matter for this example, I’m not going to cover locking for now.)

Obviously if the directory is different per person, you could use the Session scope instead of the Application scope. If you are worried about the data staying around too long, you can even add a way to flush the cache:

<cfif isDefined("url.flushmycachebaby")>
<i>run cfdirectory again</i>
</cfif>
Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments