Comments
L W wrote: Dear Sir, Please do forward a Google Wave Invitation to lvw.iv4 (at) gmail (dot) com, at your earliest convenience? Much appreciated!
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..

SYS-CON.TV
Today's Top SOA Links


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:

<CFINVOKE COMPONENT="browser"
METHOD="IsIE"
RETURNVARIABLE="result">
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:

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

<CFINVOKE COMPONENT="browser" METHOD="IsIE"
RETURNVARIABLE="result">
<CFINVOKEARGUMENT NAME="browser" VALUE="#browserid#">
</CFINVOKE>
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:

<CFINVOKE COMPONENT="user" METHOD="GetFullName"
USERID="#FORM.userid#" RETURNVARIABLE="name">
<CFINVOKE COMPONENT="user" METHOD="GetEMail"
USERID="#FORM.userid#" RETURNVARIABLE="email">
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:

<CFOBJECT COMPONENT="user" NAME="objUser">
<CFINVOKE COMPONENT="#objUser#" METHOD="Init"
USERID="#FORM.userid#">
<CFINVOKE COMPONENT="#objUser#" METHOD="GetFullName"
RETURNVARIABLE="name">
<CFINVOKE COMPONENT="#objUser#" METHOD="GetEMail"
RETURNVARIABLE="email">
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:

<CFSCRIPT>
objUser=CreateObject("component", "user");
objUser.Init(FORM.userid);
name=objUser.GetFullName();
email=objUser.GetEMail();
</CFSCRIPT>
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:

<CFOBJECT COMPONENT="user" NAME="SESSION.objUser">
<CFINVOKE COMPONENT="#SESSION.objUser#"
METHOD="init" USERID="#FORM.userid#">
Simple as that. Now any application code could invoke methods within the object in the SESSION scope:

<CFINVOKE COMPONENT="#SESSION.objUser#"
METHOD="GetFullName" RETURNVARIABLE="name">
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:

<CFCOMPONENT EXTENDS="user">
...
</CFCOMPONENT>

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:

ACCESS="remote"

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.

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

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

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

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


Your Feedback
Shirley Keddy wrote: 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. Shirley
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE