Placing executable code in a separate file



You can place executable code in a separate file from the main component definition page. By placing the method execution code in a separate file, you can separate property initialization code, meta information, and the method definition shell from the executable method definition code. This technique lets you modularize your code and helps prevent CFML pages from getting too long and complex.

To separate the component method code, use a cfinclude tag on the component definition page to call the page that contains the component method code.

Note: If your method takes arguments or returns data to the page that invokes it, the cfargument tag and the cfreturn tag must be on the component definition page, not on the included page.

Create a component method by using the cfinclude tag

  1. Create a tellTime.cfc file with the following code:

    <cfcomponent> 
        <cffunction name="getUTCTime"> 
            <cfinclude template="getUTCTime.cfm"> 
        <cfreturn utcStruct.Hour & ":" & utcStruct.Minute> 
        </cffunction> 
    </cfcomponent>
  2. Create a ColdFusion page with the following code, and save it as getUTCTime.cfm in the same directory as tellTime.cfc:

    <cfscript> 
        serverTime=now(); 
        utcTime=GetTimeZoneInfo(); 
        utcStruct=structNew(); 
        utcStruct.Hour=DatePart("h", serverTime); 
        utcStruct.Minute=DatePart("n", serverTime); 
        utcStruct.Hour=utcStruct.Hour + utcTime.utcHourOffSet; 
        utcStruct.Minute=utcStruct.Minute + utcTime.utcMinuteOffSet; 
        if (utcStruct.Minute LT 10) utcStruct.Minute = "0" & utcStruct.Minute; 
    </cfscript>

    In the example, the getUTCTime method definition calls the getUTCTime.cfm file with the cfinclude tag. The getUTCTime.cfm code calculates the UTC time representation of the current time and populates a structure with hour and minute values. The method in tellTime.cfc then uses the information in the structure to return the current UTC time as a string to the calling page. The included page must not include a cfreturn statement.