3

We are running ColdFusion MX7.

One problem we have is that we have a lot of functions that we use in a lot of our pages. It would be nice to have them live in the 'Global' ColdFusion scope rather than having to include them in all of our pages.

Is there a way to do this that does not involve custom tags or the like?

I know we could attach some objects to the Application or Server scopes, but then we have to reference them as such.

Simply adding them to the global scope would be perfect.

EDIT

Thanks to the suggestions, here is what I came Up with. Basically, for each request in the OnRequestStart function, assign to a properly named variable in the client scope the function reference (this.functionName).

Application.cfc:

<cfcomponent OUTPUT="FALSE">
<cfset This.name = "MyApp">
<CFSET This.clientManagement = true>
<CFSET This.SessionManagement = true>

<CFFUNCTION NAME="Coalesce" OUTPUT="FALSE" access="public">
    <CFARGUMENT NAME="ARG1">
    <CFARGUMENT NAME="ARG2">

    <CFIF ARG1 NEQ "">
        <CFRETURN ARG1>
    <CFELSE>
        <CFRETURN ARG2>
    </CFIF>
</CFFUNCTION>

<cffunction name="onRequestStart">
    <CFSET CLIENT.COALESCE = this.COALESCE>
</cffunction>

</cfcomponent>

The pages that are under this application happily respond to the call:

<CFOUTPUT>#COALESCE("ONE","TWO")#</CFOUTPUT>

Works great!

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
Tom Hubbard
  • 15,820
  • 14
  • 59
  • 86
  • 2
    "but then we have to reference them as such.", not really. CF will look for the function in Application scopes for you. So if you have funcA() in Application scope, you can just call funcA() and it'll work. You don't need to call Application.funcA() – Henry Jun 25 '09 at 20:27
  • I was not able to get a public function to respond from the application scope (with application.cfc). Did I miss something? – Tom Hubbard Jun 26 '09 at 11:38
  • Thanks for sharing the code you ended up using. Instead of adding it to the question you should post it as an answer. – Patrick McElhaney Jun 26 '09 at 12:29
  • Re: Henry's comment, while it will work, it's a best practice to always scope your variables. It will reduce conflicts. – Dan Sorensen Dec 14 '09 at 16:41

2 Answers2

6

There's no such thing as "global scope".

If you're talking about variables scope in every page, you can try including the UDF's inside Application.cfm.

If you use Application.cfc, look up onRequest() in the CF7 doc.

Henry
  • 32,689
  • 19
  • 120
  • 221
2

One option I have been happy with is to create a services (or similiar named) component in Application.cfc. Add all of your functions to this component and create it when the application is created. This will improve load time as the functions are cached in the application and also make the functions accessible to any file in that application. Of course then you would be required to call the function like application.services.myUsefulFunction()

Nick Van Brunt
  • 15,244
  • 11
  • 66
  • 92