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)

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.

IoT & Smart Cities Stories
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
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...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
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...