views:

114

answers:

2

I'm migrating an old app that uses application.cfm to use an application.cfc. The CFM sets a few globals such as

<cfset dsn = "myDSN">

I've tried putting that line of code in onApplicationStart, onRequestStart, etc. but trying to print that value out in a test page results in an error. Setting a value in the application scope (e.g. application.dsn) works fine of course but I'm under a tight deadline and can't rock the boat by doing a site-wide search and replace for each global.

I know putting these in scopes is the right thing to do but, for the time being, is there any way to switch to using Application.CFC but still create unscoped global variables?

+7  A: 

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

Ken Redler
That did the trick although I gave a vote to the answer below also since that's also good to know in the future.
DaveBurns
+3  A: 

You'll need both Application.cfc and Application.cfm. Move all of the major code from Application.cfm to the proper portions 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 outside of all of the functions:

<cfinclude template="Application.cfm" />

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

<cfoutput>#dsn#</cfoutput>

If you define variables.dsn anywhere inside of the CFC, you're putting the variable into the variables scope of the CFC, which is private to the CFC. By defining it in the CFM, then including the CFM, it's kept in the variables scope of the page request.

iKnowKungFoo
If you take this approach, I'd name the included file something like globals.cfm, to avoid any confusion about whether it is treated like Application.cfm is in previous versions of CF (which it is not).
Adam Tuttle
Did anyone test this interesting approach? Maybe I'm doing something wrong with my 3 one-line templates, but it doesn't work for me (CF9). Tried application.cfm and globals.cfm. And to be honest, I didn't expect it to work, because I don't see, why setting a variable in an included file should "leave" the scope of the including cfc and make the var globally available. And why directly setting the var within the application.cfc outside of functions should not work the same way. The onRequest() "Mixin" approach works as expected.
Andreas Schuldhaus