Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

ColdFusion MX Overview – An Introduction to Components

Page 5 — An Introduction to Components


In ColdFusion 5, modular code was basically a choice between a <CFINCLUDE>, a custom tag, or a User Defined Function. Depending on who wrote the modular code in ColdFusion 5, it could have been implemented in different ways, commented in different ways, and organized in the file system in different ways. I’ve seen custom tags that make my head spin! If only there was some way to standardize how we organize functionality and documentation. Fusebox offers a sweet framework recommendation to structure and document your application as a whole, but there wasn’t anything about CF5 at a code level that encouraged structured, modular, well documented coding.

Introducing CFMX Components!

Without further ado, i’ve drummed up a simple component for your eyes to feast on. This code lives in a file called “dateExample.cfc”.

dateExample.cfc

<CFCOMPONENT>
 <CFFUNCTION NAME=”getTomorrow”>
   <CFRETURN dayofweekAsString(dayofweek(dateadd(“d”, 1, now())))>
 </CFFUNCTION>
</CFCOMPONENT>

The first thing you should notice about components is that they live in files that end with a .cfc extension instead of the usual .cfm. Just like custom tags, the name of the .cfc file is also the name of your component. In this example, my component name is “dateExample” since the file name is “dateExample.cfc”. Everything is wrapped between <CFCOMPONENT> and </CFCOMPONENT> tags which create an envelope for the component. And hey!… isn’t that our <CFFUNCTION> from the last set of examples? Yep! CFCs can contain one or many <CFFUNCTION>s.

Even before we get into the good stuff, here’s how you might call this component from a regular ColdFusion page called “test.cfm”. For the purpose of the example, we’ll assume that test.cfm and dateExample.cfc are in the same directory.

test.cfm

<CFINVOKE
 COMPONENT = “dateExample”
 METHOD  = “getTomorrow”
 RETURNVARIABLE = “tomorrowName”>

Tomorrow is <CFOUTPUT>#tomorrowName#</CFOUTPUT>.

Test.cfm would return the name of the current day in a sentence. Notice how we use the METHOD attribute to specify which function we want to call.

You now have a basic understanding of how to write components, and you can prove it with a component that tells you what day tomorrow will be. Yay! Wasn’t that simple? Now you’re wondering what the big deal is. How does this allow me to maintain well documented code in a structured way? Why wouldn’t I just write a UDF the way I already know how?

Maybe we should have a look at one more example.

Comments