我正在迁移一个使用application.cfm来使用application.cfc的旧应用。 CFM设置了一些全局变量,例如
<cfset dsn = "myDSN">
我已尝试将这行代码放在onApplicationStart,onRequestStart等中,但尝试在测试页中打印出该值会导致错误。在应用程序范围内设置一个值(例如application.dsn)当然可以正常工作,但是我处于一个紧迫的截止日期之前,不能通过在整个站点范围内进行搜索并替换每个全局。
我知道将这些放在范围内是正确的做法,但目前是否有任何方法可以切换到使用Application.CFC,但仍然可以创建无范围的全局变量?
答案 0 :(得分:10)
尝试将其放在onRequest()
而不是onRequestStart()
。
答案 1 :(得分:4)
您需要Application.cfc和Application.cfm。将所有主要代码从Application.cfm移动到Applicaiton.cfc的适当部分。
然后,这可能是Applicaiton.cfm中的唯一一行:
<cfset variables.dsn = "myDSN" />
现在返回Application.cfc并将其添加到所有函数之外:
<cfinclude template="Application.cfm" />
在test.cfm上,现在应该能够输出不带作用域前缀的dsn变量:
<cfoutput>#dsn#</cfoutput>
如果在CFC内的任何位置定义variables.dsn,则将变量放入CFC的变量范围,CFC是CFC专用的。通过在CFM中定义它,然后包括CFM,它保存在页面请求的变量范围内。
答案 2 :(得分:1)
我自己也在努力,我会给你解决方案。请注意,这适用于CF9,我不知道其他版本(在以前的版本中有onRequest和AJAX调用的问题)。基本上,有必要在Application.cfc中使用onRequest函数。这是一个基本模板:
<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.