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 2

Using ColdFusion Components Part 2

Last month I introduced you to ColdFusion Components - CFCs for short. Following a brief introduction to the world of objects, we looked at CFCs and their syntax, and simple calling conventions using <CFINVOKE>. This month we'll continue this topic.

Using CFCs
In the last issue we created a CFC called browser (used to perform browser identification tests) and invoked methods in it like this:

The IsIE method (which checks to see if Microsoft Internet Explorer is the browser in use) in the browser component takes an optional argument named browser and defaults to the CGI variable of the browser in use if not provided.

There are two different ways to pass arguments to component methods. The first is simply to append an attribute to the <CFINVOKE> call:

RETURNVARIABLE="result" BROWSER="#browserid#">
Alternatively, the <CFINVOKE ARGUMENT> tag may be used, as follows:

<CFINVOKEARGUMENT NAME="browser" VALUE="#browserid#">
The second format provides greater control over passing optional arguments (as <CFINVOKEARGUMENT> may be used conditionally or within a loop if needed). Both calling conventions do the exact same thing, so use whatever suits you best.

Alternate Invocation Options
<CFINVOKE> provides a simple way to invoke component methods, but it's by no means the only way to do so. <CFINVOKE>, as used above, actually does two things:

  1. It loads the component.
  2. It then invokes a specific method.
Multiple <CFINVOKE> calls to the same component (perhaps to different methods within the component) will each be loaded separately. As such, any processing performed within the component (initializing variables, for example) must be performed for each invocation individually, and processing is not shared between those instances.

Suppose you created a "user" component that you then invoked to obtain a user name and then invoked again to obtain a user e-mail address. Your calls might look something like this:

Notice that you'd need to pass the user ID to each invocation (as the second one would have no knowledge of the first). In addition, within the component the actual lookup would have to happen twice - once for each invocation.

A better solution would be to treat the CFC as an object, loading it using the <CFOBJECT> tag:

While <CFINVOKE> both loaded the component and executed a method, here those two steps have been separated from each other. <CFOBJECT> loads the component into an object (named using the NAME attribute). The <CFINVOKE> tags then use that existing object to invoke specific methods.

The first <CFINVOKE> call in-vokes an Init method, passing the user ID to the component. Now subsequent <CFINVOKE> calls need not pass the user ID, as the same instance of the component is being used in each call and it already knows the ID. Furthermore, within the component any user processing (perhaps reading the user from a database) would have to occur just once instead of for every method invocation.

The fact that CFCs may be used as objects creates another interesting opportunity. Although ColdFusion custom tags may not be used within <CFSCRIPT> blocks (because tags may not be used in <CFSCRIPT>), objects can be, because there is a function equivalent of <CFOBJECT> - the CreateObject() function. Since components can be loaded as objects, they can be used within <CFSCRIPT>. Here's the <CFSCRIPT> version of the previous code block:

objUser=CreateObject("component", "user");
As you can see, components can be used exactly like objects, and the <CFSCRIPT> syntax is particularly useful to developers who have worked with objects in other development languages.

There are other invocation options too:

  • HTML forms may be submitted to CFC files directly (specifying the CFC file as the ACTION).
  • URLs may invoke CFCs directly, passing the method and any parameters as URL parameters in the query string.
  • Flash MX ActionScript code (using the NetServices functions) can invoke component methods (essentially a client/server application, Flash on the client invoking CFCs on the server).
  • CFCs may be consumed as Web services (more on that later).
As you can see, CFCs are very flexible and very accessible. In fact, a single well-written CFC will likely be used in all sorts of ways - and often in ways you never anticipated.

Note: As a rule, within a CFC your code should never make any assumptions about the environment it's running in and where requests are coming from. Even though CFC code has access to all scopes, you're better off never assuming that any particular scope or variable exists or that requests are being made by specific clients or specific platforms. This way your code will be far more portable.

Data Abstraction
We've now started talking about data abstraction (something I first mentioned last month). Look at the preceding code - if the user ID is passed in one invocation, how do subsequent invocations have access to it?

To explain this, take a look at the user component (file user.cfc) in Listing 1. It's by no means complete, but it is working code, and will help explain how data abstraction works.

The first thing you'll notice is that there is code that is not in any function:

<!--- Initialize variables --->
<CFSET THIS.initialized=FALSE>

Any code inside a component but not inside a particular function is constructor code, code that's automatically executed when a component is first loaded. This line of code sets a flag called initialized to FALSE. The flag is stored in the THIS scope; a special scope within a component, it persists as long as the instance of the component persists, so anything stored within it is available to all invocations. Once initialized is placed in the THIS scope, that flag is available to subsequent method calls.

The first method, Init, requires that a user ID be passed to it. It then retrieves the user record for that ID using a <CFQUERY>. If the record was retrieved (i.e., the ID was valid and usable), then Init saves a copy of it in the THIS scope and sets the initialized flag to TRUE.

The next two methods return data. GetFullName returns the user's full name (concatenating the first and last names) and GetEMail returns the e-mail address. Both methods first check to see if THIS.initialized is TRUE (if it isn't, Init was never called or the Init failed, and no user record would be present to return), and then return data from the query saved in the THIS scope. This way data needn't be reread each time it's needed.

The benefit of code like this is that, once initialized, user information is readily available throughout an application. There's no need to refer to underlying databases. If databases changed, or if additional business logic were needed or special formatting were to be applied, all that code could be localized inside the component, transparent to any invocations.

You'd need more code in the user component, of course. It would also need to know how to add, update, delete, search, and more. But you get the idea.

Persistent CFCs
It gets better. You now know that components can be loaded into objects (using the <CFOBJECT> tag or the CreateObject() function). Just as they can be loaded as standard variables (in the VARIABLES scope), they can also be loaded into persistent scopes (like SESSION or APPLICATION).

For example, if your application required users to log in, you might want to keep an instance of their user object in a SESSION variable so that it would persist for as long as the SESSION did. Look at this code:

METHOD="init" USERID="#FORM.userid#">
Simple as that. Now any application code could invoke methods within the object in the SESSION scope:

This will work for APPLICATION too if needed. The object will persist for as long as the scope does, and any data in the component's THIS scope will persist too.

Using Inheritance
Inheritance is a subject that really deserves a column unto itself, but here are the basics.

You've created a user object (file user.cfc) that abstracts all user processing. Now you need an administrator object that does everything the user object does plus a bit more. Rather than copy all the code into a new administrator.cfc file, you could create your component like this:


EXTENDS implements inheritance. As administrator.cfc extends user.cfc, everything in the user component will be accessible in the administrator component as well (even the THIS scope). Within the administrator component you could:

  • Create additional methods that will be available only in administrator.
  • Overwrite specific user methods by creating methods in administrator with the same names as methods in user.
Inheritance is an advanced concept, so I won't go into more detail just yet. But when you need it, know that it's there waiting for you.

Creating Web Services
Web services are all the rage now. Web services are simply the next generation of distributed computing, a mechanism by which to create and use parts of applications anywhere, even remotely. In Web service lingo, Web services are produced (made available for use) and then consumed (used) by other applications.

Web services aren't a ColdFusion invention. In fact, they're one of the few technologies that just about every major player in the space is backing and supporting. .NET uses them extensively, and J2EE applications support services too. This broad industry support means that Web services are going to become very important, they are going to succeed.

In addition, Web services employ several key technologies, all of which are open and standard:

  • HTTP
  • XML
  • SOAP (Simple Object Access Protocol)
  • WSDL (Web Services Description File)
  • UDDI (Universal Description, Discovery, and Integration)
ColdFusion MX makes consuming Web services incredibly simple - all it takes to consume a service is a single CFML tag (the same <CFINVOKE> tag you've already seen). I'll be covering Web services extensively in a future column, but for now I just want to explain how they're created in ColdFusion.

Are you ready? Hold tight - this gets really complicated. To create a Web service (that may be accessed by remote applications, not just ColdFusion), simply add the following to your <CFFUNCTION> tags:


That's it! By specifying that methods are accessible remotely, Cold-Fusion will make them accessible as Web services (even generating the required WSDL automatically on-the-fly).

More on this in future columns.

Securing Components
The last subject I need to mention is security. Custom tags don't need special security options. They're accessible by ColdFusion only locally so they're as secure as the rest of your ColdFusion code. But CFCs are accessible as Web services, which means they may be accessed remotely too. So how can you secure them against unauthorized access?

CFCs actually feature two security options that may be used individually or together:

1.   Each method may take an optional ACCESS attribute (as just seen). By default, ACCESS="public", which means that the method is available to all ColdFusion code on your own server (just like custom tags). To make components accessible remotely, you must explicitly state ACCESS="remote". (Additional ACCESS levels control what ColdFusion code on your server may access methods, if needed.)

2.   Methods may also have associated ROLES - groups of users that requesters must have been authenticated as in order to invoke a method. By default, no ROLES are used, but if needed this attribute provides a mechanism to grant or deny access based on login information.

So, by default, CFCs are as secure as custom tags. But if you need greater security (to manage greater accessibility), the support for that is there, ready for you to use.

As you've just seen, ColdFusion Components are incredibly powerful and flexible. They provide the power of objects while retaining the simplicity of CFML (supporting advanced object features such as inheritance and constructors), can be invoked and used in all sorts of ways, can be made to persist if needed, and can even be accessed as Web services. CFCs are the new building blocks that all ColdFusion applications should be built with. Learn them, use them, and take your code to a whole new level.

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 (1) 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
Shirley Keddy 11/05/02 02:27:00 PM EST

A site glitch -
After entering our access code for CFDJ and using the Search box users do indeed get a list of articles. By clicking on a title you can see the first page of the article - however, when you use the Next link to view subsequent pages, you are taken to sub.cfm page which provides information for subscribing to CFDJ (which we already do).

The only way to see the article is to note the Vol and Issue numbers and go to the archives and access the article through the issue content listing of articles.

This is not user-friendly!
Thanks in advance for looking at this.

@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 ...