Invoking CFC methods with the cfinvoke tag

The cfinvoke tag can invoke methods on a CFC instance or invoke CFC methods transiently. You can also use the cfinvoke tag to invoke CFC methods from within a CFC.

This section describes the following topics:

Invoking methods of a CFC instance

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

To invoke a method of a component instance using the cfinvoke tag:

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


View comments in LiveDocs