Caching Functions: Creating variables that are executable.
This is too cool. Either that or I am too much of a geek; or both.
There was a discussion of CF_Talk about the best way to make use of reusable functions (User definable Functions or UDF's). Dominic Watson pointed out you can "declare" the functions with out executing them and then store them in the application scope (i.e in memory). It is like storing a variable in memory except that they contain executable code instead of data. Much like how you can instantiate a CF class (component) and then stick the instance of that object in memory. This makes sense with components because of the overhead involved with creating an object. So instead of creating the object every time you want to use it, you cache it in memory.
Well is seems that you can do the same thing with functions.
Now that is a very cool idea. What is even cooler is that you can then create a structure (for ppl not acquainted with structures, think of them as a one dimensional array with their own scope, like FORM or URL variables) and then store the functions in the structure so they are all in one neat little package. I called them "mini CFC's".
The function onApplicationStart and fires up when ever the app is started
--->
<cffunction name="onApplicationStart">
<!---
Include your UDF's
--->
<cfinclude template="theUdfs.cfm">
<cfinclude template="theUdfs2.cfm">
<!---
Create a struct to hold the functions
--->
<cfset application.udfs = StructNew()>
<!---
Load the functions into the struct and load it in memory (The application scope)
--->
<cfset application.udfs.MyFunction1 = MyFunction1>
<cfset application.udfs.MyFunction2 = MyFunction2>
<cfset application.udfs.MyFunction3 = MyFunction3>
</cffunction>
<!--- Then, to avoid verbosity when calling a udf, I'd add this line in OnRequestStart() --->
<cffunction name="onRequestStart">
<cfset variables.udfs = application.udfs>
</cffunction>
I asked Dominic more about it and he said
When ColdFusion processes a 'page' with a udf (either cffunction or scripted 'function'); the function is parsed and created as an *object* in memory (a special function type object). By 'calling' the function without the () you are actually referencing the object itself rather than invoking the function that it represents. So, the following code just makes the application.udfs.MyFunction1 variable a reference to the function named 'MyFunction1':
Dave Watts (always a wealth of knowledge) further elucidated on this matter and said that:
This is a pretty good explanation, but it's even simpler than that. Functions are really just one more type of variable, just like queries, structures, arrays, etc. They contain executable code instead of data, that's all. And, you're not "calling" the function unless you have the parentheses after the function name:
You can read the full thread here:
http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:56438


There are no comments for this entry.
[Add Comment]