Another approach to template caching

2007 August 03
tags: ColdFusion · Code
by Nick

Caching is an important mechanism for improving application performance and reducing server load. There are currently a few features built-in to ColdFusion to assist developers with caching which work very well. The "cachedwithin" and "cachedafter" attributes in cfquery provide an excellent way to persist query results in memory for a specified length of time. So, for query results that don't require real-time data, this is great to use. The other, is cfcache.

One down-side to using cached queries is that you are prevented from using cfqueryparam. However, I understand that CF8, which launched this week, addresses this issue. But... what about complex display logic which requires several different sources of data, layers of components, conditional logic, remote web-service calls, etc...? The cfcache tag is great and supports server and client-side file-based caching and all, however, the downside is that you either cache the whole page, or you don't.

I recently wanted a solution that provided cfcache-like functionality, but the flexibility to set different expirations for each section of content on a page. In addition, I wanted each content section to be able to be "mirrored" on subsequent pages without having to be re-generated, but other sections to be unique. Also, I wanted it to be file-based... I realize this has more of performance impact, but I like that the content will persist if the server is restarted or the database connection is lost, or whatever... it's also more scalable for huge sites like the one I'm currently working on.

The result is a custom tag which can be called as follows (roughly):

not cached

<!--- cache latest news for 4 hours --->
<cf_cache name="latestNews" cachedWithin="#createTimeSpan(0,4,0,0)#" namespace="global">
cached display logic goes here
</cf_cache>

not cached

The logic in the custom tag will create a static html file for "latestNews" in the "global" namespace if it doesn't already exist, or if it has expired, based on the generated content within the tags... otherwise, it will display the cached version. If this is unique content, I can use the template name to further distinguish it.

All cache on a single page can be forced by appending 'flushcache=1' to the URL string. Similarly, all cache can be preserved by setting this parameter equivalent to false.

Please feel free to download the code and send me any feedback.

No Responses leave one →

Leave a Reply