Reputation: 85
I'm wondering if anyone has thoughts on what they think the best way to store and access custom function in coldfusion.
What I'm currently doing: At the moment I have a variety of CF-Components in which I store related functions. For example:
<cfcomponent displayname="Math">
<cffunction name="func1">
<!---Code--->
</cffunction>
<!---Function 2, Function 3, etc.---->
</cfcomponent>
Then when I need to use them on a page I do the following
<cfset lv_math_obj = createobject("component","cfc.Math")>
<cfset variable = lv_math_obj.myFunction(parameter)>
Why I Like It: The above code is easy to read and understand, and my functions are precompiled!
Why I dislike it: Objects are not supposed to be a list of functions that work independently of one another.
Has anyone thought of a better way to store and access custom functions?
Upvotes: 1
Views: 218
Reputation: 1793
You can place often used functions in the request scope.
<cffunction name="OnRequestStart" access="public" returntype="boolean" output="false">
<cfargument name="TargetPage" type="string" required="true"/>
<cfinclude template="/udfs/global.cfm">
<cfreturn true />
</cffunction>
I find this very easy to work with. It is also possible to place the component or functions in the application scope but as Henry pointed out this can be really annoying when you are developing or changing a website.
If you place your functions in the request scope you need to make a reference to the function. For example the included /udfs/global.cfm file could contain the following function:
<cffunction name="func1">
<!---Code--->
</cffunction>
<cfset request.func1 = func1>
In the application you can call this function with the following statement:
<cfset test = request.func1()>
Upvotes: 0
Reputation: 32915
What you're currently doing has nothing wrong per-se, but for each request you're instantiating cfc.Math
which shouldn't break a sweat in CF9+, but not necessary.
You can optimize it by instantiate once in onApplicationStart()
and put the object into the Application
scope. However, doing so would make invoking an UDF rather verbose, i.e. Application.math.func1()
. You may set Variables.math = Application.math
in onRequest()
then all your CFM will have access to math.anyFunc()
. To make your UDFs accessible to any CFC methods you can consider putting the UDFs in Form
or Url
scope to get away with needing to use scope prefix.
Furthermore, when your cfc.Math
is updated, you'd need to flush out the old copy by doing what most frameworks do (e.g. ?init=true
, detects that in onRequestStart()
, and carry out the re-initialization), or restart the application.
IMO the simplest way would be putting the UDFs into a math.cfm
and include it before I need to use them.
Upvotes: 1