Ask Ben: Simple Data Caching In ColdFusion

<!--- Check to see which mode this tag is executing in. --->
<cfswitch expression="#THISTAG.ExecutionMode#">
 
	<cfcase value="Start">
 
		<!--- Define tag attributes. --->
		<cfparam
			name="ATTRIBUTES.Key"
			type="string"
			/>
 
		<cfparam
			name="ATTRIBUTES.Timeout"
			type="numeric"
			default="#CreateTimeSpan( 0, 0, 30, 0 )#"
			/>
 
		<cfparam
			name="ATTRIBUTES.ExpirationDate"
			type="numeric"
			default="0"
			/>
 
		<cfparam
			name="ATTRIBUTES.Cache"
			type="any"
			/>
 
 
		<!---
			In the beginning of the tag, we just want to try
			to get the data before the contents of the tag
			execute. However, this will throw an error if
			the data doesn't exist. If so, we want the tag
			to fully execute.
		--->
		<cftry>
 
			<!--- Try to output the cached data. --->
			<cfset WriteOutput(
				ATTRIBUTES.Cache.GetData( ATTRIBUTES.Key )
				) />
 
			<!---
				Exit out of tag. This will make sure that the
				contents and code enclosed in this ColdFusion
				custom tag do not execute.
			--->
			<cfexit method="exittag" />
 
			<!--- Catch any errors that happened. --->
			<cfcatch>
 
				<!---
					There was an error getting the data.
					Therefore, the cache was not updated
					and we need to let the tag fully
					execute.
				--->
 
			</cfcatch>
		</cftry>
 
	</cfcase>
 
	<cfcase value="End">
 
		<!---
			Now that the tag has fully executed, let's store the
			generaged output in the cache. If the user provided
			an expiration date, we will use that, otherwise, we
			will calculate expiration based on the timeout.
		--->
		<cfif NOT Val( ATTRIBUTES.ExpirationDate )>
 
			<!---
				Calculate expiration date and store it back into
				the attributes scope.
			--->
			<cfset ATTRIBUTES.ExpirationDate = (Now() + ATTRIBUTES.Timeout) />
 
		</cfif>
 
 
		<cfset ATTRIBUTES.Cache.SetData(
			ATTRIBUTES.Key,
			THISTAG.GeneratedContent,
			ATTRIBUTES.ExpirationDate
			) />
 
	</cfcase>
 
</cfswitch>

For Cut-and-Paste