Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Using ColdFusion Components Part 1

Using ColdFusion Components Part 1

In the May issue of CFDJ (Vol. 4, issue 5) I introduced you to ColdFusion MX - the just-released ColdFusion upgrade that is nothing short of revolutionary. As I explained in that article, CFMX features lots of incredible new technologies and features. But the one I think is most important (in terms of how it will, or should, impact your development) has to be ColdFusion Components. This month (and continued next month) I'd like to explain in depth what CFCs are and how they should be used.

CFCs Are Objects, Kind Of
To understand CFCs it's important to understand a bit about objects.

But first, a necessary qualification - CFML is not an object-oriented language, and CFCs don't provide all the features and functionality typically provided by OOP languages. This isn't a bad thing - actually, I think the opposite is true. Objects have too long been the exclusive property of languages and syntactical rules that are unnecessarily complicated. There's no reason for developers using rapid development languages, like CFML, not to be able to leverage this type of technology too. Thus the CFC.

At their simplest, and at the risk of offending OOP purists, objects are simply reusable application bits. They are black boxes - magical things that do stuff, whatever you define that stuff to be. If this sounds a bit like custom tags, well, there are similarities, but objects typically do more than custom tags. For example, they often contain not just code (like custom tags) but also data, allowing data and any code that accesses it to be cleanly encapsulated. Objects usually have multiple entry points (methods). They provide a mechanism to automatically run initialization code regardless of the entry point (a constructor). Objects can be adapted and modified, leveraging existing code without actually modifying (and potentially breaking) any of it in the process (inheritance).

If this all sounds a little esoteric, an example should help clarify things.

Objects Demystified
Almost any ColdFusion developer has had to deal with users in their applications. You've probably done things like:

  • Used <CFQUERY> to check a user-provided name and password
  • Used returned database rows to obtain a user's name and e-mail address
  • Used programmatic flow-control to grant or deny access to features based on login name, access level, or security equivalences
  • Saved and read user preferences like colors, fonts, language choices, topic and category selections, and more
  • Added new users or updated or deleted existing ones
  • ...and so on
In doing these things, how many places in your code ended up referring to users in some way, shape, or form? How much code did you end up repeating (or copying and pasting)? What would happen if the user tables had to change, and how much code would that affect? What if your databases were replaced entirely by an LDAP server, or new sets of rules and levels had to be applied? How much did nonprogrammers have to know about the guts of your user management to be able to do simple things like display a personalized welcome message?

In an object world you'd have written your application very differently. You'd have created a user object - a black box that contained everything and anything you'd ever need to do with users, as well as all the database (or LDAP) access needed to perform those operations.

To perform operations on a user, you'd then create an instance of the user object, perhaps specifying the user ID in the process. Then you'd be able to use methods (functions) like:

  • Add()
  • Delete()
  • Update()
  • Get()
Or even more specific ones, like:
  • VerifyPassword()
  • GetEMail()
  • GetColorPrefs()
  • GetDisplayName()
...the idea being that any and all user processing would happen inside the user object. You'd never access user tables directly. Actually, you wouldn't even know (or care) that the data is being stored in a table - that wouldn't matter at all. You'd just invoke methods as needed, letting the code inside the object do its thing.

This is the kind of functionality made possible using CFCs.

Introducing CFCs
Now that you know what CFCs are, let's look at how they're created. True to ColdFusion and its mission, CFCs are incredibly easy to create. In fact, only two steps are involved:

1.   Create a file with a .CFC extension (this distinguishes CFCs from ColdFusion templates, which have a .CFM extension).
2.   Use four new tags to create the components, define their functions and arguments, and return a value.

The four new tags are:

  • <CFCOMPONENT>: Defines a CFC
  • <CFFUNCTION>: Defines the functions (methods) within a CFC
  • <CFARGUMENT>: Defines the arguments (parameters) that a function accepts
  • <CFRETURN>: Returns a value or result from a function
Other than these new tags (which, incidentally, are the same ones used to create tag-based, user-defined functions in CFMX), CFCs are plain CFML. Within a CFC you can use any tag, function, custom tag, component, and more.

Creating CFCs
Listing 1 offers a simple example to clarify all this, a component that does basic browser identification (determines the browser being used).

This is a simplified version of a file named browser.cfc. As you can see, the code is wrapped between <CFCOMPONENT> and </CFCOMPONENT> tags. The component itself has a single function, IsIE (as in "Is Internet Explorer"), and is defined and named with a <CFFUNCTION> tag. Within the function a variable named result is defined and initialized; if the browser identifier contains the Microsoft Internet Explorer identifier, that variable is then set to "yes." And finally, <CFRETURN> returns "result."

This isn't a complete example yet (although it's actually workable as is), but it's a good starting point.

How would you use this code? Save it as browser.cfc, and in the same directory create a test.cfm file that should contain the following:

<!--- Invoke browser CFC --->
<CFINVOKE COMPONENT="browser"
METHOD="IsIE"
RETURNVARIABLE="result_ie">

<!--- Feedback --->
<CFOUTPUT>
Your browser is:<BR>
IE: #YesNoFormat(result_ie)#<BR>
</CFOUTPUT>

<CFINVOKE> is a new tag in CFMX and one of its jobs is to invoke component methods. As seen here, <CFINVOKE> takes the name of the component (browser, minus the extension) and the method to execute. To access any returned data, the RETURNVARIABLE attribute provides the name of a variable to contain whatever the function returns.

You can try running this code. If you are running IE it will tell you so, and if not it'll tell you that too.

Writing Complete CFCs
Now that you're familiar with how CFCs work, take a look at Listing 2, a complete version of browser.cfc. This new version is a bit more complex, so let's walk through it together.

<CFCOMPONENTS> now contains four methods:

  • IsIE: Checks for IE, returning "yes" or "no"
  • IsNetscape: Checks for Netscape, returning "yes" or "no"
  • IsDreamweaver: Checks for Dreamweaver (the browser built into Dreamweaver), returning "yes" or "no"
  • Identify: Checks for all three, returning "IE" if Internet Explorer, "NS" if Netscape, "DW" if Dreamweaver, and an empty string if unknown (none of the above)
You'll notice that we've added two attri-butes to every <CFFUNCTION>:
  • RETURNTYPE: Specifies the type of the return data. This is used to validate returned data (if it's the wrong type, an error would be thrown) and to document the function.
  • HINT: A text description used when the function is documented (more on that in a moment)
In the earlier version of browser.cfc the code checked the CGI variable HTTP_ USER_ AGENT to determine the browser used. But that's not ideal because these functions should be able to check any browser ID passed to them (assuming they're not always checking the current browser).

And so, each of these new functions takes an optional parameter defined with the <CFARGUMENT> tag, which can be used in two distinct ways:

1.   To check for required parameters, set REQUIRED="yes"; if the specified parame-ter isn't passed, an error will be thrown. Additional validation may be performed by specifying a TYPE, in which case ColdFusion checks that the parameter exists and that it is of the correct type.
2.   To check for optional parameters, set REQUIRED="no" and specify the DE-FAULT value to be used if the parameter isn't provided.

In all four functions <CFARGUMENT> defines a single parameter, browser, allowing calling code to pass any string as needed. If the parameter isn't provided, the default CGI variable is used as before.

The first three functions are basically the same as the one we looked at earlier, but the fourth, identify, which provides an alternate interface to the browser identification code, warrants special mention. Instead of checking for a specific browser (as the three prior functions do), this one checks for them all and returns an ID based on which browser it is. Rather than copy all of the previous code into this new function, it simply invokes those functions directly. But it doesn't invoke them using the <CFINVOKE> tag seen previously; rather, it uses them as functions (which they are), making the syntax much cleaner and simpler.

Listing 3, a revised version of test.cfm, can be used to test all the functions.

It's as simple as that.

Documentation
I mentioned that HINT and RETURNTYPE are used in documenting CFCs. So where is the documentation?

CFCs may be introspected - a fancy way of saying that they can be asked to describe themselves. As they know all about their functions and what they do, they can fulfill this request quite admirably.

Here are two ways to introspect a CFC:

1.   Execute a CFC directly in your browser, providing a URL directly to it (something like http:// local-host/path/browser.cfc). ColdFusion will generate cleanly formatted documentation on-the-fly, using everything it knows about the component (including the specified HINTs).
2.   If you're using Dreamweaver MX, select the Components tab in the application window to have Dreamweaver scan for available CFCs. Dreamweaver will then build a tree control containing all components and their methods. You may right-click on any component or method for more information (or to edit the code), and may even drag a method into the editor window to generate a complete <CFINVOKE> tag.

There's more to introspection, but we're out of space for now.

Summary
CFCs provide the power of objects with the simplicity of CFML. As seen here, CFCs are created using four new tags, saved as .CFC files, and invoked using the <CFINVOKE> tag. But we've barely scratched the surface here. In fact, thus far we've been using CFCs merely as glorified custom tags. Next month I'll show you alternate ways to invoke CFCs, how to make them persist, how to use constructors and inheritance, and much more. And we'll come back to the user explanation we started with.

More Stories By Ben Forta

Ben Forta is Adobe's Senior Technical Evangelist. In that capacity he spends a considerable amount of time talking and writing about Adobe products (with an emphasis on ColdFusion and Flex), and providing feedback to help shape the future direction of the products. By the way, if you are not yet a ColdFusion user, you should be. It is an incredible product, and is truly deserving of all the praise it has been receiving. In a prior life he was a ColdFusion customer (he wrote one of the first large high visibility web sites using the product) and was so impressed he ended up working for the company that created it (Allaire). Ben is also the author of books on ColdFusion, SQL, Windows 2000, JSP, WAP, Regular Expressions, and more. Before joining Adobe (well, Allaire actually, and then Macromedia and Allaire merged, and then Adobe bought Macromedia) he helped found a company called Car.com which provides automotive services (buy a car, sell a car, etc) over the Web. Car.com (including Stoneage) is one of the largest automotive web sites out there, was written entirely in ColdFusion, and is now owned by Auto-By-Tel.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Paul Weston 11/22/02 03:34:00 PM EST

Er, make that GREY background...

Paul Weston 11/22/02 03:32:00 PM EST

Where you post your reply at the bottom of the article, if you look to the right then you'll see the 'source code' link on the blue background.

Frank Perrotta 07/16/02 10:44:00 AM EDT

When reviewing an article online,
if the author refers to code as in listing 1, what link or area would I go to to review the code that is being described?

@ThingsExpo Stories
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...