RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Build a Better ColdFusion Cache Tag

ColdFusion's <cfcache> tag is great, but it caches only whole HTML pages and most templating systems won't play along. Learn how to develop a custom tag that allows you to cache arbitrary sections of ColdFusion-generated pages.

aching is an essential strategy for improving the performance of your applications, and ColdFusion offers much pre-packaged functionality to assist in this area, including a number of application server caching settings in the ColdFusion Administrator. ColdFusion also offers caching options directly through ColdFusion tags. For example, developers can use the <cfquery> tag's cachedAfter and cachedWithin settings to cache the results of database queries and the <cfcache> tag for its direct support of user-interface caching.

The <cfcache> tag is not without its limitations, however. It works very well when you want to cache a whole HTML page, but if you want to cache just part of a page, you are out of luck. The "page" is the smallest unit that <cfcache> can process. Such a restriction might be reasonable for simple applications, but almost any sophisticated application design uses some kind of templating system to assemble complex interfaces from a variety of individual ColdFusion scripts. As such, most modern application designs don't allow whole pages to be cached since to do so requires a single script to serve as the root point for the whole application.

Many ColdFusion frameworks, like the popular Fusebox or the newer Mach-II, require that all traffic go through the same ColdFusion script (usually named something like index.cfm). If you place a <cfcache> tag on this page, only the first page accessed ever gets displayed.

Luckily, it's quite easy to write a cache tag that can work with sections of pages, and this article describes a script that does just that. The tag is named CacheOMatic (click here to download it), so the first step is to create a file called CacheOMatic.cfm and save it to a directory where ColdFusion custom tags are stored (the paths indicated under the setting "Custom Tag Paths" in the ColdFusion Administrator, generally a default path that looks something like C:\CFusionMX\CustomTags).

When you want to cache a section of a page, you surround it with the tag <cf_CacheOMatic>, as in:

Here's some stuff to cache!

While you want to support a plain vanilla version of the tag, you also will add some optional parameters. The CacheOMatic tag will take the three inputs shown in Table 1, all optional.

Name The "Key" of the Cache
scope The scope in which you want to store this data; corresponds with ColdFusion scopes: application, session, and server
exp How long until the cache expires
Table 1. Optional Inputs for CacheOMatic

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date