ColdFusion 9.0 Resources |
Invoking CFC methods with the cfinvoke tagThe 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. Invoking methods of a CFC instanceTo invoke a component method of a CFC instance, use the cfinvoke tag and specify the following:
The following procedure creates an application that displays the current UTC and local time.
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. Invoking component methods transientlyIn ColdFusion pages or components, the cfinvoke tag can invoke component methods without creating a persistent CFC instance. To invoke a component method transiently, use the cfinvoke tag and specify the following:
The following procedure creates an application that displays the local time.
Using the cfinvoke tag within the CFC definitionYou can use the cfinvoke tag to invoke a component method within the component definition; for example, to call a utility method that provides a service to other methods in the component. To use the cfinvoke tag in this instance, do not create an instance or specify the component name in the cfinvoke tag, as the following example shows: <cfcomponent> <cffunction name="servicemethod" access="public"> <cfoutput>At your service...<br></cfoutput> </cffunction> <cffunction name="mymethod" access="public"> <cfoutput>We're in mymethod.<br></cfoutput> <!--- Invoke a method in this CFC. ---> <cfinvoke method="servicemethod"> </cffunction> </cfcomponent> Note: When you invoke a method from within the component
definition in which you define the method, do not use the This scope,
because this resets the access privileges.
Invoking methods by using dynamic method namesThe cfinvoke tag is the only way to efficiently invoke different component methods based on variable data (for example, form input). In this case, you use a variable name, such as Form.method, as the value of the method attribute. In the following example, the user selects a report from a form: <select name="whichreport"> <option value="all">Complete Report</option> <option value="salary">Salary Information</option> </select> The cfinvoke tag then invokes the appropriate method, based on what the user selected: <cfinvoke component="getdata" method="#form.whichreport#" returnvariable="queryall"> |