1

我的 application.cfc 以:

<cfcomponent extends="org.corfield.framework">

稍后的void function setupApplication() output="false" {

我有

// tools
include "initapp.cfm";

initapp.cfm 除了函数之外什么都没有。像:

<!--- Helper functions --->
<cfscript>
string function stripHTML(str) output="false" {
return REReplaceNoCase(arguments.str,"<[^>]*>","","ALL");
}

application.stripHTML = stripHTML;

</cfscript>

函数的性质与会话无关。有没有更好的方法让函数在全球范围内可用?

4

2 回答 2

5

如果您尝试将辅助函数放在一起以在 CFC 中使用,则一种选择可能是使用 component.cfc 文件。

使用 component.cfc 文件

所有 CFC 都会自动扩展 ColdFusion WEB-INF/cftags/component.cfc 组件。(WEB-INF 目录位于配置了嵌入式 J2EE 服务器的 ColdFusion 上的 cf_root/wwwroot 目录中。当您在 J2EE 服务器上部署 ColdFusion 时,它位于 cf_root 目录中。)此 CFC 作为零长度文件分发。您可以将它用于您希望 ColdFusion 应用程序服务器实例中的所有 CFC 继承的任何核心方法或属性。

Note: When you install a newer version of ColdFusion, the installation procedure replaces the existing component.cfc file with a new version. Therefore, before upgrading, you should save any code that you have added to the component.cfc file, and then copy the code into the new component.cfc file.

If that solution is TOO global you can extend your helper cfc, but it has to be done in every cfc and doesn't answer your one-time-set-it-and-forget-it idea. See Using CFCs effectively

If your helper functions are for use in .cfm files, I'd do like Adam suggested. I usually put my helper functions in a "tools" cfc located in a CFC folder and make it an application scoped cfc.

function onApplicationStart(){
    application.tools = createObject("component", "cfc.tools");
}

One of my helper functions logs the time it takes to index a solr collection. Using it looks like

<cfset application.tools.logSolrIndex('collectionName',getTickCount()-start,qFileList.recordCount)>

Last resort: If you had to stick with an include for use outside of the application.cfc, I might simply include initapp.cfm onRequest() before you include your page.

于 2012-12-07T12:26:32.807 回答
3

将函数放入库 CFC 中,然后将该 CFC 的实例放入onApplicationStart().

也就是说,如果您随后在其他 CFC 中引用此应用程序范围的 CFC,您将有点破坏封装,这是一个考虑因素(不一定是交易破坏者,而是一个考虑因素)。

您可以查看某种依赖注入方法来缓解这种情况(例如:ColdSpring

无论我最终以哪种方式去做,恐怕我都不会像你那样做。

于 2012-12-07T09:15:16.117 回答