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

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.

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.

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.

Use of this website implies agreement to the following:

Copyright Information

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

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

No Printing or saving of web pages

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


Linking to this website

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


Warranties

This 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.