How can I include mappings into Application.cfc from external property file?

Deadly 提交于 2019-12-04 07:33:25

Mappings can't be set in onApplicationStart(), they must be set in the pseudo constructor of Application.cfc, and they must be set on every request.

It's also important to note that the application scope is not available at this point, therefore if you need to cache anything you'll need to use the server scope. You can cache your mapping struct to the server scope and just set it into this.mappings each request.

<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>

If you intend to keep you ini file in the webroot, you should make it a .cfm template and start it with a <cfabort>. It will work just the same but will not be readable

ApplicationProperties.ini.cfm

<cfabort>
[mappings]
/foo=c:/bar/foo
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!