
181
DEVELOPING
COLDFUSION 9 APPLICATIONS
Building Blocks of ColdFusion Applications
Las
t
upda
te
d 8/5/2010
For detailed reference information on the cffunction tag, see the
CFML Reference
.
Defining CFCs with related methods
When defining CFCs, it is good programming practice to organize related methods in one CFC. For example, you
could place all methods that perform operations related to a user, such as
addUser
,
editUser
, and
storeUserPreferences
, in one CFC. You can group related mathematical functions into one CFC. A CFC can also
contain all the methods and properties necessary for a shopping cart. The following CFC contains two cffunction tags
that define two component methods,
getEmp
and
getDept
. When invoked, the component methods query the
ExampleApps database. The cfreturn tag returns the query results to the client, or page, where the method was
invoked.
<cfcomponent>
<cffunction name="getEmp">
<cfset var empQuery="">
<cfquery name="empQuery" datasource="cfdocexamples" dbtype="ODBC">
SELECT FIRSTNAME, LASTNAME, EMAIL
FROM
tblEmployees
</cfquery>
<cfreturn empQuery>
</cffunction>
<cffunction name="getDept">
<cfset var deptQuery="">
<cfquery name="deptQuery" datasource="cfdocexamples" dbtype="ODBC">
SELECT
*
FROM
tblDepartments
</cfquery>
<cfreturn deptQuery>
</cffunction>
</cfcomponent>
Placing executable code in a separate file
You can place executable code in a separate file from the main component definition page. By placing the method
execution code in a separate file, you can separate property initialization code, meta information, and the method
definition shell from the executable method definition code. This technique lets you modularize your code and helps
prevent CFML pages from getting too long and complex.
To separate the component method code, use a cfinclude tag on the component definition page to call the page that
contains the component method code.
Note:
If your method takes arguments or returns data to the page that invokes it, the cfargument tag and the cfreturn tag
must be on the component definition page, not on the included page.
Create a component method by using the cfinclude tag
1
Create a tellTime.cfc file with the following code:
<cfcomponent>
<cffunction name="getUTCTime">
<cfinclude template="getUTCTime.cfm">
<cfreturn utcStruct.Hour & ":" & utcStruct.Minute>
</cffunction>
</cfcomponent>
2
Create a ColdFusion page with the following code, and save it as getUTCTime.cfm in the same directory as
tellTime.cfc:
Содержание COLDFUSION 9
Страница 1: ...Developing Applications ADOBE COLDFUSION 9...