ColdFusion Components

ColdFusion components (otherwise known as CFCs) are a powerful feature of ColdFusion that allows developers to introduce object oriented programming techniques into their ColdFusion skillset. These techniques have proven to be an important part of object oriented languages such as Java, C++, VB etc

A ColdFusion component is basically a collection of functions that relate to a given entity, like for example, a Customer. You could create a ColdFusion Component that is responsible for the programming logic regarding your customer records.

For example, you could create one ColdFusion component called customer.cfc that contains five functions to perform database queries. One could create a new customer record, another function could update customer records, another to retrieve, one for deleting, and one for listing your customers.

Other functions could be included too, but you get the idea. By doing this, you would have all your programming logic for customers in one place, which has got to be a good thing - you're effectively separating your presentation from your logic.

OK, so you're thinking, "I could have done that using a <cfinclude> tag!". True, however, ColdFusion components are much more powerful than the <cfinclude> tag.

Benefits of using ColdFusion Components

Example of a ColdFusion Component

This example is a very simple version of a ColdFusion Component. It retrieves all records from a table in a database. Here, the datasource name has been stored in an application variable called application.dsn but you could just as easily use the datasource name directly.

You can do much more with components but the purpose here is to give you a basic introduction to the syntax.

Save the above code in a file called customer.cfc and you now have a ColdFusion component!

Calling a ColdFusion Component

The following code calls the above component. (Note: This code will reside in a different file to the component. You could call it say, ListCustomers.cfm

In the above example, the component has been saved into a folder called components so I have to use dot notation to specify the folder. This is followed by the name of the component. Method is the name of the function within the component that I want to call (in this case retrieveCustomers). Returnvariable is the name I want to give to the variable that is returned by this function so that I can use it within the current page.

Once you've called the component, you can then output the rest of your page.

That's all there is to creating, and calling a simple ColdFusion component. In the next lesson, we'll see how easy it is to turn a component into a web service.