12 ways to reuse your ColdFusion code
posted under category: ColdFusion on April 8, 2010 by Nathan
It's no doubt that code reuse is an important part of programming. Here's a list of ways you can do it while you're programming in ColdFusion.
<cfinclude template="file.cfm">
This is the most basic server-side include, which pulls one file into another. There is no way to send parameters to the included file (besides setting variables before the include). The included template can by dynamic using a#variable#
. Unlike classic ASP, the file is included only when the tag executes.include "file.cfm"
This is the cfscript version of thecfinclude
tag and behaves similarly.<cf_file attribute1="value1">
This is Custom Tag syntax. You can use this to send parameters at an included file. In this example, file.cfm exists either in the relative current directory, in a custom tag path specified by your Application.cfc file, or in a custom tag path specified in the CF Administrator.<cfmodule [name= or template=] >
Similar to the custom tag model, but you can use any file with a relative path.<cfimport namespace="imported"> ... <imported:file />
Specify a directory and namespace, and you can use this JSP style include. Thecfimport
tag must be applied on every template you wish to use the namespaced file set in. Imported files behave like custom tags in that they use attributes and can have a closing tag, but it can also be used for JSP tagsets.<cffunction name="reusable"></cffunction>
Defines a reusable function, method or subroutine of your application. You can type this anywhere in your application, except within another function.function reusable() {}
This is the cfscript version ofcffunction
. Since CF9, it can use extra syntax to give more metadata and control like the tag-based version has.<cfcomponent> ... </cfcomponent>
This is the root element of a .cfc file. Any code within is executed immediately upon instantiation (see cfobject). The methods (functions) within are executed upon request.component { ... }
This is the cfscript version of defining a CFC. This also provides the only way to write cfscript without thecfscript
tags.<cfobject >
Creates an instance of (a.k.a. "instantiates") an object, which could be Java, .NET, a web service, or a variety of others, but in this case, we are talking about creating an instance of a ColdFusion Component (CFC) or ColdFusion web service.createObject("component", "myComponent")
new myComponent()
cfscript versions ofcfobject
and traditionally the easiest way to create an instance of any CFC.<cfinvoke>
Invokes a method on an object or webservice, instantiated or not.
That's a big list!