【问题标题】:Is onApplicationStart is good Idea in ColdFusion?onApplicationStart 在 ColdFusion 中是个好主意吗?
【发布时间】:2009-12-20 02:15:55
【问题描述】:

我必须在ColdFusion 中使用变量(查询结果集),它将从其他应用程序数据库中获取结果,并存储在 Coldfusion 应用程序中。

主要思想是我只需要在服务器启动时调用其他应用程序数据库并将结果缓存在本地。而且我需要在我的应用程序的其他页面中读取变量。我不会在任何页面中覆盖该变量。

通过谷歌搜索,我发现“onApplicationStart”对于在应用程序启动时分配变量很有用。

使用onApplicationStart 好还是有其他方法?我们可以在启动时(一次)分配一个变量。

如果onApplicationStart没问题:怎么用?也许任何清楚解释的链接都有帮助。

【问题讨论】:

  • 什么版本的 ColdFusion?如果您使用的是 CF9,请查看 CFCACHE 标签。

标签: coldfusion scope restart


【解决方案1】:

嗯,这取决于。此查询数据多久更新一次?如果它确实是不变的,那么 onApplicationStart() 是一个放置它的好地方。但是,如果它会经常更改,您只需将 Coldfusion 告诉 cache the querya certain period of time,然后您就不需要弄乱 onApplicationStart(),而是当您调用查询时它会返回缓存的结果自动(在您指定的时间段内)。

无论如何,我都会编写一个自定义函数来检索数据。然后从 onApplicationStart() 或其他地方调用它会很简单。

Startup.cfc:(随便命名)

<!--- Replace the datasource name with your db name --->
<cffunction name="getStartupQuery" hint="Returns a query recordset for startup">
    <cfargument name="datasource" required="no" type="string" default="OtherAppDB">
    <!--- Init the query variable --->
    <cfset var result = queryNew("id")>

    <!-- Get the query dataset --->
    <cfquery name="result" datasource="#arguments.datasource#">
         YOUR QUERY HERE
    </cfquery>

    <cfreturn result>
</cffunction>

Application.cfc:(仅重要部分)

<cffunction name="onApplicationStart">
    <!--- init the startup.cfc, then retrieve the data
    and save it to the application scope. Remember the component name must match
    your component above --->
    <cfset var startup = createObject("component", "startup")>
    <cfset application.varFromOtherDB = startup.getStartupQuery()>
    <cfreturn true>
</cffunction>

现在,您应该可以使用以下方法从应用程序中的任何 CFM 或​​ CFC 访问此变量:

<cfset myNewVar = application.varFromOtherDB>
or
#application.varFromOtherDB#

如果您使用 onApplicationStart() 方法,我强烈建议您实施一种方法来重新初始化应用程序。例如,see this other discussion

【讨论】:

  • 嘿,丹,太好了。我确信除了应用程序启动之外我不需要重新初始化这个查询,因为来自其他数据库的查询值很少更改。所以我不想每次都调用它。但令人惊讶的是,在我的应用程序中我们没有“Application.cfc”(我认为他们最近从 CF7 升级到 CF8,所以没有实现它)。但是我们使用 Application.cfm 文件来设置所有页面通用的变量。您认为Appliaction.cfc中的上述代码我们可以在Application.cfm中使用(包含在所有页面中)还是需要创建新的Application.cfc?
  • 你在使用 application.cfm 和 标签吗?我对 application.cfm 方法没有经验,所以我会听从其他人来回答这个问题。大部分代码将保持不变。您可能需要研究使用 application.cfm 设置应用程序范围变量的适当方法:livedocs.adobe.com/coldfusion/8/htmldocs/…
  • 来自 livedocs.adobe.com/coldfusion/8/htmldocs/AppEvents_01.html ,“如果您的应用程序有一个 Application.cfc 和一个 Application.cfm 或 onRequestend.cfm 页面,ColdFusion 将忽略 CFM 页面。”我相信使用其中一种是更好的做法。 onRequest 方法将为您提供在实际执行 cfm 页面之前运行脚本的相同能力。
  • 我同意 Eddie 的观点,即您应该使用其中一种。在我诉诸 onRequest() 之前,我会检查您是否正在使用 application.cfm。如果您不使用 application.cfm,那么设置 application.cfc 会很容易。它的运行频率似乎超出了您的实际需要。
  • 是的,我在 ApplicationSettings.cfm 文件中使用 application.cfm 和 标记,但没有使用 application.cfc。在 application.cfm 我包括 ApplicationSettings.cfm 文件顶部
猜你喜欢
  • 2010-11-05
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 2010-12-28
  • 2010-10-19
相关资源
最近更新 更多