Initializing instance data
Some components have instance data, data that persists as long as the component instance exists.
For example, a shopping cart component might have instance data that includes the IDs and
quantities of items the user puts in the shopping cart. Instance data is often shared by several
methods that can create, delete, or modify the data. Components whose methods you invoke
transiently, without first instantiating the component, do not typically have instance data.
You initialize instance data at the top of the component definition, before the method definitions.
ColdFusion executes this code when it instantiates the component; for example, when a
tag creates the component instance. Because this code executes only when the instance
cfobject
is created and it typically "constructs" properties of the component, instance data initialization
code is sometimes called constructor code.
You can use any CFML tag or function in constructor code, and the code can perform any
ColdFusion processing, such as querying a database or data validation and manipulation. If one
component extends another, the parent component's constructor code executes before the child
component's constructor code.
Note: ColdFusion does not require you to put the initialization code at the top of the component
definition; however, it is good programming practice to do so.
The following example shows constructor code for a shopping cart CFC:
<cfcomponent>
<!--- Initialize the array for the cart item IDs and quantities --->
<cfset This.CartData = ArrayNew(2)>
<!--- The following variable has the ID of the "Special Deal" product for
this session --->
<cfset This.Special_ID = RandRange(1, 999)>
Note: For information on the This scope, see
Defining component methods
You define component methods using
defines a
getEmp
<cffunction name="getEmp" displayname="Get Employee" access="remote">
<cfquery name="empQuery" datasource="ExampleApps" dbtype="ODBC" >
SELECT FIRSTNAME, LASTNAME, EMAIL
FROM tblEmployees
</cfquery>
<cfreturn empQuery>
</cffunction>
Because component methods are ColdFusion functions, most of their features and coding
techniques are identical to those of user defined functions. For more information on using the
tag to create functions, see
cffunction
Functions," on page
Tip: To improve performance, avoid using the
tag or CFScript assignment statements.
236
Chapter 11: Building and Using ColdFusion Components
cffunction
method:
191.
"The This scope" on page
tags, as the following example shows, which
Chapter 10, "Writing and Calling User-Defined
cfparam
tag in CFC methods. Instead, use the cfset
242.
Need help?
Do you have a question about the COLDFUSION MX 61-DEVELOPING COLDFUSION MX and is the answer not in the manual?
Questions and answers