开发者

Possible to create an unscoped global in application.cfc?

开发者 https://www.devze.com 2023-01-02 16:58 出处:网络
I\'m migrating an old app that uses application.cfm to use an applic开发者_开发技巧ation.cfc. The CFM sets a few globals such as

I'm migrating an old app that uses application.cfm to use an applic开发者_开发技巧ation.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?


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


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.


Having wrestled with this myself, I'll give you my solution. Note that this works on CF9, I don't know about other versions (there is an issue with onRequest and AJAX calls in previous versions). Basically, it's necessary to have the onRequest function in your Application.cfc. Here's a 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's 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号