Contents > Developing ColdFusion MX Applications > Building and Using ColdFusion Components > Building ColdFusion components > Defining component methods Putting method executable code in a separate file PreviousNext

Putting method executable code in a separate file

You can put component 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 returns data to the page that invokes it, the cfreturn tag must be on the component definition page; it cannot be on the included page.

To create component method 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 function 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.)


Contents > Developing ColdFusion MX Applications > Building and Using ColdFusion Components > Building ColdFusion components > Defining component methods Putting method executable code in a separate file PreviousNext

ColdFusion 9 | ColdFusion 8 | ColdFusion MX 7 | ColdFusion MX 6.1 | ColdFusion MX | Forums | Developer Center | Bug Reporting

Version 6.1

Comments are no longer accepted for ColdFusion MX 6.1. ColdFusion 8 is the current version.