5

我在 Application.cfc 中设置映射时遇到问题 我们有不同的服务器(dev、QS、prod),每个服务器都有一些不同的路径。我想通过配置文件设置服务器特定的路径和变量。在 ApplicationStart 上,您读取 ini 文件并设置您的系统。 http://www.raymondcamden.com/index.cfm/2005/8/26/ColdFusion-101-Config-Files-AGoGo 这很好用。

通常,您在 Applcation.cfc 中设置映射,如下所示:

<!--- in Application.cfc --->
<cfset this.mappings['/components'] = "D:\Inetpub\wwwroot\myApp\components">

在普通 cfm 文件中的某个地方,我通过以下方式创建了一个名为 test 的 cfc:

<cfset t = createObject("component", "components.test")>

我只想在onApplicationsStart设置一次映射

<cffunction
    name="OnApplicationStart"
    access="public"
    returntype="boolean"
    output="false"
    hint="Fires when the application is first created.">

    <!---create structure to hold configuration settings--->
    <cfset ini = structNew()>
    <cfset ini.iniFile = expandPath("./ApplicationProperties.ini")>
    <cfset application.ini = ini>

    <!--- read ini file --->
    <cfset sections = getProfileSections(application.ini.iniFile)>

    <cfloop index="key" list="#sections.mappings#">
       <cfset this.mappings[key] = getProfileString(application.ini.iniFile, "mappings", key)>
    </cfloop>

但这不起作用,因为 this.mappings 是空的并且是下一个请求。:(

把它放到 OnRequestStart

<!--- read ini file --->
    <cfset sections = getProfileSections(application.ini.iniFile)>

    <cfloop index="key" list="#sections.mappings#">
       <cfset this.mappings[key] = getProfileString(application.ini.iniFile, "mappings", key)>
    </cfloop>

我收到无法找到组件的错误。这很奇怪。

将结构放入应用程序范围

    <cfloop index="key" list="#sections.mappings#">
       <cfset APPLICATION.mappings[key] = getProfileString(application.ini.iniFile, "mappings", key)>
    </cfloop>

如何调用我的组件?

<cfset t = createObject("component", "application.components.test")>

不工作。

所以我有3个目标。

  1. 从 ini 文件中读取所有路径和映射
  2. 在 ApplicationStart 阅读一次
  3. 在源代码中易于使用。
4

1 回答 1

7

映射不能在 onApplicationStart() 中设置,必须在 Application.cfc 的伪构造函数中设置,并且必须在每次请求时设置。

同样重要的是要注意,此时应用程序范围不可用,因此如果您需要缓存任何内容,则需要使用服务器范围。您可以将映射结构缓存到服务器范围,然后将其设置到 this.mappings 每个请求中。

<cfcomponent>
  <cfset this.name = "myapp" />

  <!--- not cached so create mappings --->
  <cfif NOT structKeyExists(server, "#this.name#_mappings")>
    <cfset iniFile = getDirectoryFromPath(getCurrentTemplatePath()) & "/ApplicationProperties.ini" />
    <cfset sections = getProfileSections(iniFile) />
    <cfset mappings = structnew() />
    <cfloop index="key" list="#sections.mappings#">
      <cfset mappings[key] = getProfileString(iniFile, "mappings", key)>
    </cfloop>
    <cfset server["#this.name#_mappings"] = mappings />
  </cfif>

  <!--- assign mappings from cached struct in server scope --->
  <cfset this.mappings = server["#this.name#_mappings"] />

  <cffunction name="onApplicationStart">
  <!--- other stuff here --->
  </cffunction>

</cfcomponent>

如果您打算将 ini 文件保留在 webroot 中,则应将其设为 .cfm 模板并以 <cfabort> 开头。它的工作原理相同,但不可读

应用程序属性.ini.cfm

<cfabort>
[mappings]
/foo=c:/bar/foo
于 2012-05-11T14:00:36.467 回答