Can I create a global unscoped in application.cfc?

I am porting an old application that uses application.cfm to use application.cfc. CFM sets several global variables, such as

<cfset dsn = "myDSN"> 

I tried to put this line of code in onApplicationStart, onRequestStart, etc., but trying to print this value on the test page results in an error. Setting the value in the application area (for example, application.dsn) works fine, but I am in a tight deadline and can’t download the boat, searching the entire site and replacing each global one.

I know this is correct, but is there currently any way to switch to using Application.CFC, but still create non-distributed global variables?

+6
scope coldfusion global-variables
source share
3 answers

Try putting it inside onRequest() instead of onRequestStart() .

+9
source share

You will need both Application.cfc and Application.cfm. Move all the main code from Application.cfm to the corresponding parts of Applicaiton.cfc.

Then, and this may be the only line in Applicaiton.cfm:

<cfset variables.dsn = "myDSN" />

Now go back to Application.cfc and add this beyond all the functions:

<cfinclude template="Application.cfm" />

Your test.cfm should now be able to output the dsn variable without the scope prefix:

<cfoutput>#dsn#</cfoutput>

If you define .dsn variables anywhere inside CFC, you put the variable in the CFC variable area, which is private to CFC. Defining it in CFM, then enabling CFM, he saved the page request in the variable area.

+4
source share

Struggling with this myself, I will give you my decision. Please note that this works on CF9, I do not know about other versions (there is a problem with onRequest and AJAX calls in previous versions). Basically, you need to have the onRequest function in your Application.cfc. Here is the basic template:

 <cffunction name="onRequest" access="public" returntype="void" output="true"> <cfargument name="targetPage" type="string" required="true"> <!--- include the requested page. ---> <cfinclude template="#arguments.TargetPage#"> </cffunction> As far as I understand it: it actually the cfinclude that enables you to access the functions. So, with this onRequest in your Application.cfc you can access the 'this' scope of the Application.cfc which would include your public functions & variables. If you want a more in depth example of this then check out Framework-1 by Sean Corfield. It does this exact thing, all API methods are contained in the Application.cfc. 
+1
source share

All Articles