Using ColdFusion components-Developing guide

You can use a CFC in two ways:

  1. You can instantiate a CFC object, which creates a CFC instance. You then invoke the methods of the instance. You can access the CFC methods and data as instance elements. You can also use the instance in the  cfinvoke  tag to invoke the CFC methods. When you instantiate a CFC, data in the CFC is preserved as long as the CFC instance exists, and ColdFusion does not incur the overhead of creating the instance each time you call a method. Instantiate CFCs to preserve data in the CFC. To ensure processing efficiency if you use the CFC more than once on a page, instantiate the CFC before you invoke its methods.Methods that are executed remotely through Flash Remoting and web services always create an instance of the CFC before executing the method.

  2. You can invoke (call) a method of the CFC without creating an instance of the CFC, which is referred to as transiently invoking a method. In this case, ColdFusion creates an instance of the CFC that exists only from the time you invoke the method until the method returns a result. No data is preserved between invocations and ColdFusion does not keep an instance of the CFC that you can reuse elsewhere in your CFML. It is considered a best practice to create an instance of a CFC before invoking any of its methods, unless your CFML request uses the CFC only once. If you transiently invoke a method frequently, consider creating a user-defined function to replace the CFC method.
    You can create persistent CFCs by assigning the CFC instance to a persistent scope, such as the Session or Application scope. This way, you can create CFCs for objects, such as shopping carts or logged-in users, that must persist for sessions. You can also create CFCs that provide application-specific data and methods.

Tags for using CFCs

The following table lists the tags that you use to instantiate or invoke a CFC. You use these tags on the CFML page on which you instantiate or invoke the CFC.

Tag

Description

Invokes a method of a CFC.

Passes the name and value of a parameter to a component method.

Creates a CFC instance.

Creates a CFC instance.

CFC invocation techniques

ColdFusion provides many ways to instantiate CFCs and invoke CFC methods. The following table lists the techniques, including the ColdFusion tags and functions that you use:

Invocation

Description

For more information

cfinvoke tag

Invokes a component method. Can invoke methods of a CFC instance or invoke the methods transiently.

See Invoking CFC methods with the cfinvoke tag in this page.

cfset tag and assignment statements

Invoke methods and access properties of a component instance.

See Using components directly in CFScript and CFML in this page.

URL (HTTP GET)

Transiently invokes a component method by specifying the component and method names in the URL string.

See Invoking component methods by using a URL in this page.

Form control(HTTP POST)

Transiently invokes a component method using the HTML form and input tags and their attributes.

See Invoking component methods by using a form in this page.

Flash Remoting

ActionScript can transiently invoke component methods.

Web services

The cfinvoke tag and CFScript consume web services in ColdFusion. External applications can also consume CFC methods as web services.

Instantiating CFCs

If you use a CFC multiple times in a ColdFusion request, or if you use a CFC with persistent properties, use the cfobject tag or CreateObject function to instantiate the CFC before you call its methods. 
The following example uses the cfobject tag to create an instance of the tellTime CFC.

<cfobject component="tellTime" name="tellTimeObj">

The following example uses the CreateObject function to instantiate the same component in CFScript:

tellTimeObj = CreateObject("component", "tellTime");

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.

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 in Passing parameters to methods.
  • If the component method returns a result, the name of the variable for the result in the  returnVariable  attribute.
    The following procedure creates an application that displays the current UTC and local time.
  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.

Invoking component methods transiently

In 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 name or path of the component, 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  cfinvoketag  in Passing parameters to methods.
  • If the component method returns a result, the name of the variable that contains the result, in the  returnVariable  attribute.
    The following procedure creates an application that displays the local time.
  1. Create the following component and save it as tellTime.cfc:

    <cfcomponent> 
    <cffunction name="getLocalTime"> 
    <cfoutput>#TimeFormat(now())#</cfoutput> 
    </cffunction> 
    </cfcomponent>

    The example defines a component with one method, getLocalTime, that displays the current time.

  2. Create a ColdFusion page, with the following code, and save it in the same directory as the tellTime component:

    <h3>Time Display Page</h3> 
    <b>Server's Local Time:</b> 
    <cfinvoke component="tellTime" method="getLocalTime">

    Using the  cfinvoke  tag, the example invokes the  getLocalTime  component method without creating a persistent CFC instance.

Using the cfinvoke tag within the CFC definition

You 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 names

The 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">

Using components directly in CFScript and CFML

You can invoke methods of a component instance directly using CFScript or in CFML tags. To invoke component methods directly, use the CreateObject function or  cfobject  tag to instantiate the component. Thereafter, use the instance name followed by a period and the method that you are calling to invoke an instance of the method. Always use parentheses after the method name, even if the method does not take any parameters. 
You can use this syntax anywhere that you can use a ColdFusion function, such as in  cfset  tags or surrounded by number signs in the body of a  cfoutput  tag.

Invoking component methods in CFScript

The following example shows how to invoke component methods in CFScript:

<!--- Instantiate once and reuse the instance.---> 
<cfscript> 
tellTimeObj=CreateObject("component","tellTime"); 
WriteOutput("Server's Local Time: " & tellTimeObj.getLocalTime()); 
WriteOutput("<br> Calculated UTC Time: " & tellTimeObj.getUTCTime()); 
</cfscript>

In the example, the three CFScript statements do the following:

  1. The CreateObject function instantiates the tellTime CFC as tellTimeObj.

  2. The first WriteOutput function displays text followed by the results returned by the  getLocalTime  method of the  tellTimeObj  instance.

  3. The second WriteOutput function displays text followed by the results returned by the getUTCTime method of the tellTimeObj instance.

    In CFScript, you use the method name in standard function syntax, such as methodName().

Invoking component methods in CFML

The following example uses CFML tags to produce the same results as the CFScript example:

<cfobject name="tellTimeObj" component="tellTime"> 
<cfoutput> 
Server's Local Time: #tellTimeObj.getLocalTime()#<br> 
Calculated UTC Time: #tellTimeObj.getUTCTime()# 
</cfoutput>

Accessing component data directly

You can access data in the component's This scope directly in CFScript and  cfset  assignment statements. For example, if a user data CFC has a This. lastUpdated  property, you could have code such as the following:

<cfobject name="userDataCFC" component="userData"> 
<cfif DateDiff("d", userDataCFC.lastUpdated, Now()) GT 30> 
<!--- Code to deal with older data goes here. ---> 
</cfif>

For more information, see  The This scope.

Invoking CFC methods with forms and URLs

You can invoke CFC methods directly by specifying the CFC in a URL, or by using HTML and CFML form tags. Because all HTTP requests are transient, these methods only let you transiently invoke methods. They do not let you create persistent CFC instances.

Invoking component methods by using a URL

To invoke a component method by using a URL, append the method name to the URL in standard URL query-string, name-value syntax. You can invoke only one component method per URL request, for example:

http://localhost:8500/tellTime.cfc?method=getLocalTime
Note:

To use URL invocation, set the access attribute of the cffunction tag to remote.

To pass parameters to component methods using a URL, append the parameters to the URL in standard URL query-string, name-value pair syntax; for example:

http://localhost:8500/corpQuery.cfc?method=getEmp&lastName=camden

To pass multiple parameters within a URL, use the ampersand character (&) to delimit the name-value pairs; for example:

http://localhost:8500/corpQuerySecure.cfc?method=getAuth&store=women&dept=shoes
Note:

To ensure data security, Adobe strongly recommends that you not pass sensitive information over the web using URL strings. Potentially sensitive information includes all personal user information, including passwords, addresses, telephone numbers, and so on.

If a CFC method that you access using the URL displays output directly, the user's browser shows the output. You can suppress output by specifying output="No" in the cffunction tag. If the CFC returns a result using the cfreturn tag, ColdFusion converts the text to HTML edit format (with special characters replaced by their HTML escape sequences), places the result in a WDDX packet, and includes the packet in the HTML that it returns to the client.

Invoking component methods by using a form

To invoke a method by using a ColdFusion or HTML form, do the following:

  • Specify the CFC filename or path in the form or  cfform  tag action attribute.
  • Specify the CFC method in a hidden form field, as follows:

<form action="myComponent.cfc" method="POST">. 
<input type="Hidden" name="method" value="myMethod">
  • Alternatively, if you use the POST method to submit the form, you can follow the filename with ?method=methodname, where  methodname is  the name of the CFC method, as shown in the following line. You cannot use this technique with the GET method.
<form action="myComponent.cfc?method=myMethod" method="POST">.
  • Create an input tag for each component method parameter. The name attribute of the tag must be the method parameter name and the field value is the parameter value.
  • Specify the access="remote" attribute in the  cffunction  tag that defines the CFC method being invoked
    If the CFC method that you invoke from the form displays output directly, the user's browser shows the output. (You can use the  cffunction  tag output attribute to disable displaying output.) If the CFC returns a result using the  cfreturn  tag, ColdFusion converts the text to HTML edit format, places it in a WDDX packet, and includes the packet in the HTML that it returns to the client.
  1. Create a corpFind.cfm file with the following contents:

    <h2>Find People</h2> 
    <form action="components/corpQuery.cfc?method=getEmp" method="post"> 
    <p>Enter employee's last Name:</p> 
    <input type="Text" name="lastName"> 
    <input type="Hidden" name="method" value="getEmp"> 
    <input type="Submit" title="Submit Query"><br> 
    </form>

    In the example, the form tag's action attribute points to the corpQuery component and invokes the getEmp method.

  2. Create a corpQuery.cfc file, specifying access="remote" for each cffunctiontag, as the following example shows:

    <cfcomponent> 
    <cffunction name="getEmp" access="remote"> 
    <cfargument name="lastName" required="true"> 
    <cfset var empQuery=""> 
    <cfquery name="empQuery" datasource="cfdocexamples"> 
    SELECT LASTNAME, FIRSTNAME, EMAIL 
    FROM tblEmployees 
    WHERE LASTNAME LIKE '#arguments.lastName#' 
    </cfquery> 
    <cfoutput>Results filtered by #arguments.lastName#:</cfoutput><br> 
    <cfdump var=#empQuery#> 
    </cffunction> 
    </cfcomponent>
  3. Open a web browser and enter the following URL:

    http://localhost/corpFind.cfm

    ColdFusion displays the search form. After you enter values and click the Submit Query button, the browser displays the results.

Accessing CFCs from outside ColdFusion and basic HTML

Flash applications that use Flash Remoting can easily take advantage of ColdFusion components for business logic. Similarly, you can export CFCs so that any application can access CFC methods as web services.
For ColdFusion component methods to communicate with Flash Remoting applications, set the access attribute of the  cffunction  tag to  remote . 
For more information on creating CFCs for Flash Remoting, see Using the Flash Remoting Service
Any application, whether it is a ColdFusion application, a Java application, JSP page, or a . Net application, can access well-formed ColdFusion components as web services by referencing the WSDL file that ColdFusion automatically generates.
To see a component's WSDL definition, specify the component web address in a URL, followed by ? wsdl ; for example:

http://localhost:8500/MyComponents/arithCFC.cfc?wsdl

For more information on using CFCs as web services, see Using Web Services

Specifying the CFC location

When you instantiate or invoke a component, you can specify the component name only, or you can specify a qualified **path. To specify a qualified path, separate the directory names with periods, not backslashes. For example, myApp.cfcs. myComponent  specifies the component defined in myApp\cfcs\myComponent.cfc. For additional information, see Saving and naming ColdFusion components in Building ColdFusion components.
ColdFusion uses the following rules to find the specified CFC:

  • If you use a  cfinvoke  or  cfobject  tag, or the CreateObjectfunction, to access the CFC from a CFML page, ColdFusion searches directories in the following order:
  1. Local directory of the calling CFML page

  2. Web root

  3. Directories specified on the Custom Tag Paths page of ColdFusion Administrator

  • If you specify only a component name, ColdFusion searches each of these directories, in turn, for the component.
  • If you specify a qualified path, such as myApp.cfcs. myComponent , ColdFusion looks for a directory matching the first element of the path in each of these directories (in this example,  myApp ). If ColdFusion finds a matching directory, it looks for a file in the specified path beneath that directory, such as myApp\cfcs\myComponent.cfc, relative to each of these directories.

Note:

If ColdFusion finds a directory that matches the first path element, but does not find a CFC under that directory, ColdFusion returns a not found_ error and does_ not_ search for another directory._

  • If you invoke a CFC method remotely, using a specific URL, a form field, Flash Remoting, or a web service invocation, ColdFusion looks in the specified path relative to the web root. For form fields and URLs that are specified directly on local web pages, ColdFusion also searches relative to the page directory.
Note:

On UNIX and Linux systems, ColdFusion attempts to match a CFC name or custom tag name with a filename, as follows: First, it attempts to find a file with the name that is all lowercase. If it fails, it tries to find a file whose case matches the CFML case. For example, if you specify <cfobject name=" myObject " Component=" myComponent ">, ColdFusion first looks for mycomponent.cfc and, if it doesn't find it, ColdFusion looks for myComponent.cfc.

Get help faster and easier

New user?