<cfset cf = createObject("component","closure.ClosureFactory") />
<cffunction name="withTransaction">
<cfargument name="block" />
<p>Begin Transaction!</p>
<cftransaction>
<cfset arguments.block.call() />
</cftransaction>
<p>End Transaction!</p>
</cffunction>
<cffunction name="dbCode">
<p>I'm a database operation!</p>
</cffunction>
<cfset operation = cf.new(dbCode) />
<p>Naked operation:</p>
<cfset operation.call() />
<p>Transacted operation:</p>
<cfset withTransaction( operation ) />
This produces the following output:
<cffunction name="withTransaction">
<cfargument name="block" />
<p>Begin Transaction!</p>
<cftransaction>
<cfset arguments.block.call() />
</cftransaction>
<p>End Transaction!</p>
</cffunction>
<cffunction name="dbCode">
<p>I'm a database operation!</p>
</cffunction>
<cfset operation = cf.new(dbCode) />
<p>Naked operation:</p>
<cfset operation.call() />
<p>Transacted operation:</p>
<cfset withTransaction( operation ) />
Naked operation:
I'm a database operation!
Transacted operation:
Begin Transaction!
I'm a database operation!
End Transaction!
The example doesn't show any bindings of variables but that would be where the real power comes in.
Does that help show where closures can be useful?I'm a database operation!
Transacted operation:
Begin Transaction!
I'm a database operation!
End Transaction!

7 responses so far ↓
1 Sammy Larbi // Mar 16, 2007 at 7:02 AM
Someone might also think of it like what a dynamic cfinclude achieves for you in a template: You can specify the surrounding code while leaving the inner code for someone else to specify. That probably just muddied the water though. =)
2 jim collins // Mar 16, 2007 at 8:57 AM
3 Sean Corfield // Mar 16, 2007 at 9:27 AM
I could bind a data source variable to the dbCode closure, both independent of the original function and of the (later) execution context. That's pretty powerful.
4 Ben Nadel // Mar 16, 2007 at 10:26 AM
After reading the above, I threw this together:
http://www.bennadel.com/index.cfm?dax=blog:585.view
I think it's neat, but again, very hacky. When you have a few minutes, if you could take a peak and let me know if you have stuff built into your Closure stuff that could handle this much more elegantly.
If you don't have time, that's cool, this stuff is FAR from time-sensitive :)
5 Sean Corfield // Mar 16, 2007 at 12:20 PM
Closures are something that make a lot of sense once you "get it" but make almost no sense until then... :)
6 Rob Cameron // Mar 16, 2007 at 1:11 PM
7 Sean Corfield // Mar 16, 2007 at 1:28 PM
The call for folks with both Ruby and ColdFusion experience produced the information I was looking for and it was passed on to the folks who needed it...
Leave a Comment