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.

IoT & Smart Cities Stories
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...