ColdFusion Components – An Introduction

One of the greatest and probably most anticipated features to come with Macromedia’s Coldfusion MX is ColdFusion Components (CFCs). In its most basic form, a CFC is a collection of code and data that’s stored in a central file. In the past, you’ve probably created a file that contained all your functions, and which you could simply include in a document to have all the functions available to you. This is a very simple application of CFCs, but, as we’ll see, it’s not the whole story.

CFCs represent an attempt by Macromedia to bring ColdFusion closer to an Object Oriented Programming (OOP) language. ColdFusion is in no way an OOP language, but thanks in part to CFCs, it does boast some of the attributes that make OOP languages so popular. For instance, ColdFusion gives developers the ability to extend a piece of code to include items from another piece of code; it also gives us the ability to transplant and reuse code across a variety of systems and applications.

So how do CFCs bring ColdFusion closer to OOP, and what’s the rest of the story?

CFCs are not your normal function inclusion pages. When you create a CFC, you gain access to many more features than you would if you created an include page that contained a bunch of functions. What exactly are these features and benefits? They include:

  • Security – you have the ability restrict access to your CFCs, and the methods within them, based on user roles and settings in your CF setup.
  • Speed – CFCs are compiled so they execute faster. Keep this in mind when building your sites, as the first time a CFC is called, it is compiled and the output is returned; you might want to run through your site before releasing it to the public. Also remember that each time you make and upload a change to your code, the CFC will have to be recompiled — but there’s no need to worry, as the server handles all this for you.
  • Extensibility – CFCs can be expanded upon and they can share methods with other CFCs, much like Java and PHP classes. CFCs can also be called externally using the SOAP protocol or URL calls, which allows you to make them available to other programmers and other languages.
  • Reusability – If you code your CFC properly and are mindful of the implications of extensibility, your CFC can be shared and moved from server to server and script to script.
  • Local Reusability – Once a CFC method is invoked on a page, it’s typically reusable throughout that page. There are some exceptions to this rule of thumb, but the potential for code reuse means you don’t have to call the function multiple times on the same page.
  • Documentation – CFCs can generate their very own documentation using the hint attributes in the cfcomponent and cffunction tags. To see this functionality at work, simply open up a CFC, for example http://www.example.com/myCFC.cfc, in a Web browser (note that you will have to login with either a RDS or Administrator login to see the page). The server will generate a page that documents myCFC.
  • Forward Thinking – CFCs are represent the future for ColdFusion; it’s my opinion that we should embrace them now and push them to the limit so that the nice folks over at Macromedia will continue to improve upon them.

In the old days before ColdFusion MX, you might have created custom tags or User Defined Functions (UDFs), or found some other way to develop reusable code. CFCs allow you to achieve this aim, while delivering the added benefits listed here.

Terminology

Before we jump into a simple CFC, we need to understand some of the key terminology.

First, a CFC is called a Component, or a ColdFusion Component, and you can think of it as a container. Now, an empty container has no value until you fill it. We fill the component with methods, which are defined by the <cffunction> tag.

Once we have a component and fill it with methods, we can then invoke specific methods, which can be found in the component, using the <cfinvoke> tag.

A Simple CFC

Now that you have a general overview of the flow and lingo, let’s put this knowledge to work so you can really grasp the concept of CFCs.

The first thing we need to do is create a new file and save it with a .cfc extension. Call this file users.cfc; we’ll use it to store all our user methods. I also recommend you store all your CFCs in a central folder called components, cfc — whatever name takes your fancy.

Now, open this file in your favorite text editor and type the following:

<cfcomponent displayname="Users CFC" hint="This is the CFC for my user stuff">  
 <!--- This function gets all the users and their  data from the DB --->  
 <cffunction name="get_all_users" hint="Gets all users in the database" returntype="query">  
   <cfquery name="get_em" datasource=#APPLICATION.db_source#>  
     select * from from users  
   </cfquery>  
   <cfreturn get_em>  
 </cffunction>  
</cfcomponent>

Save your file, so you don’t lose the work, and let’s go through the code line by line.

<cfcomponent displayname="user cfc" hint="This is the CFC for my user stuff">

This first line tells the CF server that this is a Coldfusion Component. The displayname is the name that displays when documentation is generated; the hint contains descriptive text about the CFC as a whole.

  <!--- This function gets all the users and their  data from the DB --->  
 <cffunction name="get_all_users" hint="Gets all users in the database" returntype="query" output="false">

Next we see a comment that describes what the CFC does. After the comment is a cffunction tag with the attribute's name, hint, returntype, and output setting. name presents the name of the function being called. hint presents descriptive text about this function. returntype tells the CF server what kind of data is going to be returned by this function. And finally, output tells the server whether this function acts as if it's in a <cfoutput> tag, or a <cfsilent> tag. Basically, we use the output setting to define whether we want the function to process cfoutput tags within the cffunction (output="true"), or we want those tags to be suppressed (output="false").

You have a few choices for returntype, so be sure to pick the one that suits your function. These types are pretty self-explanatory:

  • Any
  • Array
  • Binary
  • Boolean
  • Numeric
  • Date
  • Guid
  • Query
  • String
  • Struct
  • Uuid
  • Variablename
  • Void

On top of all this, we could also define access and role attributes to help control who has access to the function and its output. The roles attribute works in unison with the cflogin tag. We can define roles, etc., with the cflogin tag; those roles then dictate the specific methods a user can and cannot invoke. We could devote a whole article to this topic but, in short, roles are great for security when your application utilizes the built-in authentication of ColdFusion. If you'd like to know more about these topics, check out the ColdFusion documentation and Macromedia Website.

    <cfquery name="get_em" datasource=#APPLICATION.db_source#>  
     select * from from users  
   </cfquery>

This next snippet of code represents the actual query that we'll run against the database. You'll notice that I've used the variable #APPLICATION.db_source# instead of naming a specific datasource. This is a personal code preference, so feel free to either store this value in your application.cfml using the cfset tag, or specify the datasource name as it is set up in the CF Administrator.

    <cfreturn get_em>

Next we have to return the query to the page that called this function. As we want to return the entire query to the calling page, and because we set returntype="query", we insert the name of the query as it appears in the name attribute for the cfquery tag.

One thing to keep in mind for the cfreturn tag is that it will return only one value at a time. So if you want or need multiple values returned, you must put them in an array or structure, and then return that array or structure.

  </cffunction>  
</cfcomponent>

Finally, we close out the function and component tags.

Use and Call Your CFC

So there you have it! You've just built your first component and function. But now you need to know how to use and call it. For this we need to create a new page and save it as users.cfml or users.cfm. Once this page is opened, saved, and ready to go, insert the following line at the top of the page, before any HTML code:

<cfinvoke component="cfc.users" method="get_all_users" returnvariable="u"></cfinvoke>

The above line is our cfinvoke tag, which is used to invoke a method within a component. The break down of this is rather simple. The component="cfc.users" tells the server what component you want to grab, and where to find it. As I saved my CFC in a folder named "cfc", I had to use dot notation to tell the server the location, and which file I wanted. If you named your directory "components", your code would read: component="components.users". If you had a more complex directory structure, such as /components/users/general/, your code would resemble this: component="compontents.users.general.users"

The next part, method="get_all_users", tells the server which method we want to use. Finally we need to specify how the returned data will be referred to. For this case we have chosen a simple "u", as in user, which we've specified using returnvariable="u".

Next, we want to create the following bit of HTML and ColdFusion code to output our data:

<table width="100%"  border="1" cellspacing="0" cellpadding="3">   
 <tr>  
   <td>Users Name</td>  
   <td>Users Login</td>  
   <td>Users Email</td>  
   <td>Users Status</td>  
 </tr>  
<cfoutput query="u">  
 <tr>  
   <td>#name#</td>  
   <td>#login#</td>  
   <td>#email#</td>  
   <td>#status#</td>  
 </tr>  
</cfoutput>  
</table>

This will output a nice little table with a row of headings for each column in the table, and a new row for each corresponding row/user in the table.

You'll notice that we used the <cfoutput query="u"> tag. This allows us to quickly output the data in a query without having to use loops. The CF server will know that it needs to execute the cfoutput tag, and the code it contains, until the query reaches the end of the output.

So there you have it! You've successfully created a component and a function, invoked that method in a separate page, and output the data.

It's my hope that this article has helped you to better understand CFCs and that it has sparked your interest in learning more. This is by no means a complete overview of CFCs -- there are many topics that were hinted at, but not expanded on here. I suggest that you read the documentation found on the Macromedia Website or on your server, and check out the Macromedia Coldfusion DevNet for some great CF and CFC-specific articles. Also if you feel so inclined, drop me a note or comment here with your questions or ideas for future articles.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.