7

我正在迁移使用 application.cfm 的旧应用程序以使用 application.cfc。CFM 设置了一些全局变量,例如

<cfset dsn = "myDSN">

我尝试将那行代码放在 onApplicationStart、onRequestStart 等中,但尝试在测试页中打印该值会导致错误。在应用程序范围(例如application.dsn)中设置一个值当然可以正常工作,但是我的截止日期很紧,无法通过在站点范围内对每个全局进行搜索和替换来摇摆不定。

我知道将这些放在作用域中是正确的做法,但是目前,有没有办法切换到使用 Application.CFC 但仍然创建无作用域的全局变量?

4

3 回答 3

10

试着把它放在里面onRequest()而不是onRequestStart().

于 2010-06-09T15:04:33.420 回答
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 私有的。通过在 CFM 中定义它,然后包含 CFM,它被保存在页面请求的变量范围内。

于 2010-06-09T15:36:22.323 回答
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.
于 2010-11-22T00:03:06.853 回答