Adobe ColdFusion 8

Invoking methods of a CFC instance

To invoke a component method of a CFC instance, use the cfinvoke tag and specify the following:

  • The CFC instance name, enclosed in number signs (#), in the component attribute.
  • The method name, in the method attribute.
  • Any parameters. For information on passing parameters, see Passing parameters to methods by using the cfinvoke tag.
  • If the component method returns a result, the name of the variable that will contain the result in the returnVariable attribute.
  1. Create a file named tellTime2.cfc with the following code:
    <cfcomponent>
        <cffunction name="getLocalTime" access="remote">
            <cfreturn TimeFormat(now())>
        </cffunction>
        <cffunction name="getUTCTime" access="remote">
            <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>
            <cfreturn utcStruct.Hour & ":" & utcStruct.Minute>
        </cffunction>
    </cfcomponent>
    

    The example defines two component methods: getLocalTime and getUTCTime.

  2. Create a ColdFusion page, with the following code and save it in the same directory as the tellTime component:
    <!--- Create the component instance. --->
    <cfobject component="tellTime2" name="tellTimeObj">
    <!--- Invoke the methods. --->
    <cfinvoke component="#tellTimeObj#" method="getLocalTime" returnvariable="localTime">
    <cfinvoke component="#tellTimeObj#" method="getUTCTime" returnvariable="UTCTime">
    <!--- Display the results. --->
    <h3>Time Display Page</h3>
    <cfoutput>
        Server's Local Time: #localTime#<br>
        Calculated UTC Time: #UTCTime#
    </cfoutput>
    

This example uses the cfobject tag to create an instance of the tellTime component and the cfinvoke tag to invoke the instance's getLocalTime and getUTCTime methods. In this example, the CFC contains the functional logic in the methods, which return a result to the calling page, and the calling page displays the results. This structure separates the logic from the display functions, which usually results in more reusable code.