2012-05-11 12 views
5

Tengo problemas para establecer asignaciones en Application.cfc Tenemos diverent Server (dev, QS, prod) Cada uno con Pathes un poco diferente. Quiero configurar parámetros y variables específicos del servidor a través del archivo de configuración. En ApplicationStart, lee el archivo ini y configura su sistema. http://www.raymondcamden.com/index.cfm/2005/8/26/ColdFusion-101-Config-Files-AGoGo Esto funciona bien.¿Cómo puedo incluir asignaciones en Application.cfc desde un archivo de propiedades externo?

Normaly configura asignaciones en Applcation.cfc así:

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

En algún lugar de un archivo normal de pies cúbicos por minuto que instatiate una prueba llamada a través de CFC:

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

Quiero configurar solamente las asignaciones una vez en 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> 

Pero esto no funciona porque this.mappings está vacío y la próxima solicitud. :(

poner esto a 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> 

consigo un error que el componente no se puede encontrar. Esto es extraño.

Poner la estructura en Alcance de uso

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

¿Cómo llamar a mi componente?

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

No funciona.

Así que tengo 3 objetivos.

  1. leer todos pathes y las asignaciones de archivo ini
  2. leerlos una vez en ApplicationStart
  3. el uso fácil en el código fuente.

Respuesta

7

Las asignaciones no se pueden establecer enApplicationStart(), se deben establecer en el pseudoconstructor de Application.cfc y se deben configurar en cada solicitud.

También es importante tener en cuenta que el alcance de la aplicación no está disponible en este momento, por lo tanto, si necesita almacenar algo en la memoria caché necesitará usar el ámbito del servidor. Puede almacenar en caché su estructura de asignación en el ámbito del servidor y simplemente configurarlo en cada una de las solicitudes.

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

Si tiene intención de mantenerlo archivo ini en el Webroot, usted debe hacer una plantilla .cfm e iniciarlo con un cfabort <>. Funcionará de la misma manera pero no será legible

ApplicationProperties.ini.cfm

<cfabort> 
[mappings] 
/foo=c:/bar/foo 
+0

Muchas gracias, esto me da un gran paso en la dirección correcta. Pero debido a esta línea Obtengo un "error no encontrado" cuando llamo a una página que no está en webroot. – inog

+0

No quiero codificarlo. ¿Alguna idea para este dilema del huevo o la gallina? – inog

+0

Eso es porque llama a expandpath() relativo a la ubicación actual del archivo. Tendrás que usar una ruta absoluta, he actualizado mi respuesta para mostrar esto –

Cuestiones relacionadas