Try an online ColdFusion class for free!
Additional Resources

Reusing Code and Writing Functions

In this lesson of the ColdFusion tutorial, you will learn...
  1. To include files with <cfinclude>.
  2. To to use Application.cfm and OnRequestEnd.cfm.
  3. To to write user-defined functions.

Writing reusable code results in time and money savings, more consistent and bug free code, and the ability to hide complex code from less seasoned developers. We'll cover several basic code reuse techniques in this lesson.

Including Files

Including files in ColdFusion is made simple with the <cfinclude> tag, which takes a single attribute: template. The template attribute points to the file to include. ColdFusion first looks for the included file relative to the current directory. If it cannot find it, it then looks in directories mapped in ColdFusion Administrator.

Syntax
<cfinclude template="path_to_file">

Note that a ColdFusion tag cannot be opened in a calling file and then closed in an included file or vice versa. The ColdFusion code in the included file must be syntactically valid on its own.

A Note on Security

If included files are under the web root, they can be accessed just as any other file can. If they have an extension such as .inc then the browser may display them as plain text. With other extensions, the browser may attempt to download the file. If the included file is a ColdFusion file and a user navigates to it, the server will try to process the file and may return errors. As a precaution, you may want to place your included files in a directory above or outside of the web root. This will prevent users from accessing the files directly.

Code Sample: ReusingCode/Demos/index.cfm

<html>
<head>
<title>Runners Home&trade;</title>
<link href="Styles/Main.css" rel="stylesheet">
</head>

<body>
<cfinclude template="Includes/NavBar.cfm">

<div id="greeting">
 <cfoutput>The time is #TimeFormat(Now(),"h:mm tt")# on #DateFormat(Now(), "mmmm d, yyyy")#.</cfoutput>
</div>

<table align="center" cellpadding="10" cellspacing="0" width="100%" height="100%" id="hometable">
---- Code Omitted ----
</table> <cfinclude template="Includes/Footer.cfm"> </body> </html>
Code Explanation

The above code is relatively straightforward. It contains to included files: Includes/NavBar.cfm and Includes/Footer.cfm.

Application.cfm and OnRequestEnd.cfm (see footnote)

Whenever a ColdFusion page is called, the ColdFusion Application Server checks the current directory for a file called Application.cfm. If Application.cfm is not found in the current directory, ColdFusion looks for the file in the parent directory and continues to look up the tree until it gets to the root directory of the file system. As soon as the file is found, ColdFusion stops looking up the tree and prepends the found Application.cfm to the called page.

Application.cfm is often used for the following tasks:

  • Control state management variables and set the application name with <cfapplication>.
  • Set default global variables such as data source names and file paths.
  • Set custom error handling using <cferror>.

Application.cfm should not used for including code to be output to the browser, such as a common header.

When and only when an Application.cfm file is found, ColdFusion will also look for a file called OnRequestEnd.cfm in the same directory. If it finds OnRequestEnd.cfm it will append it to the called file. OnRequestEnd.cfm is sometimes used for outputting debugging information or logging information about the page.

User-defined Functions

User-defined functions are used to make common tasks easier and to make code more modular and easier to read.

Defining and Calling Functions

Functions are defined with the <cffunction> tag as follows. Like built-in functions, user-defined functions can receive arguments. Arguments are defined using the <cfargument> tag. If no default is defined with the default attribute, then the argument is required.

Syntax
<cffunction name="function_name" returntype="type">
 <cfargument name="arg" type="type" default="default">
</cffunction>

Here is an example user-defined function for adding numbers.

Code Sample: ReusingCode/Demos/UDF.cfm

<html>
<head>
<title>User-defined Function</title>
</head>

<body>
<cfset total = addNums(1)>
<cfoutput>#total#</cfoutput>
</body>
</html>

<cffunction name="addNums" returntype="numeric">
 <cfargument name="num1" type="numeric">
 <cfargument name="num2" type="numeric" default="0">
 <cfargument name="num3" type="numeric" default="0">
 <cfset sum=num1 + num2 + num3>
 <cfreturn sum>
</cffunction>
Code Explanation

Notice that user functions are called in the same way as built-in functions.

Exercise: Creating a File2Table Function

Duration: 20 to 30 minutes.

In this exercise, you will modify RunningLog.cfm to include a function that creates a table from a tab-delimited text file.

  1. Open ReusingCode/Exercises/RunningLog.cfm in your editor.
  2. Create a function called File2Table that takes two arguments: the path to the file and an array of the table headers.
  3. Modify the page so that the function contains all the processing code that loads the file and creates and returns an HTML table.
  4. If the file cannot be opened, the function should return "File not found".
  5. the function and send the result to the browser.

Add formatting functionality to the function. For example, make the border size and the background color of the table controlled by the function call.

The function currently has the headers hardcoded in. This is not great for reuse. Change this so the function excepts a Headers array and loops through the array to output the headers.

Exercise: Creating a Function Library

Duration: 5 to 10 minutes.

In this exercise, you will move the function you created in the last exercise into a function library and then include that library in RunningLog2.cfm with <cfinclude>.

  1. Open ReusingCode/Exercises/RunningLog.cfm in your editor and save it as RunningLog2.cfm.
  2. Cut the File2Table function and paste it in a new file. Save the new files as Functions.cfm.
  3. Add code to RunningLog2.cfm so that it includes the new function library.

Reusing Code and Writing Functions Conclusion

Using includes and functions are two common ways of writing reusable code. Very often developers will save common functions in an include file (e.g, functions.inc), so they don't have to copy and paste functions into scripts to make use of them.

Footnotes

  1. These are covered more in the lesson on Session and Application Management

To continue to learn ColdFusion go to the top of this page and click on the next lesson in this ColdFusion Tutorial's Table of Contents.
Last updated on 2009-02-21

Use of http://www.learn-coldfusion-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm