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

ColdFusion Components

A powerful tool for CF developers

I'm writing this article a few weeks before MAX takes place. I'll be one of the unfortunate few unable to join everyone for the festivities. I am keeping a close eye on the Blackstone development though, and can't wait to start writing about it in this column.

As a side note, I will be at the Powered by Detroit conference next April (mentioned in Simon's Community Column in last month's issue of CFDJ); more details on that to come (www.poweredbydetroit.org/).

This month, we're going to talk about ColdFusion Components, or CFCs as they are more commonly known. CFCs were one of the most significant features put into the ColdFusion MX release. If you haven't read last month's article on user defined functions, and are unfamiliar with them, you may want to read that before going further. User defined functions allow you to take snippets of functionality and put them into their own little package. CFCs take this concept one step further and allow you to combine data and functionality into its own little package.

The Elements of a ColdFusion Component
If you've done any development with ColdFusion, it is likely that you already know what a ".cfm" template is. You put ColdFusion code in a .cfm template and the Web server knows to send requests for that file to the ColdFusion server for processing. ColdFusion components are contained in their own file, with the extension ".cfc". The extension is how ColdFusion distinguishes the difference between ColdFusion templates (.cfm) and ColdFusion Components (.cfc).

There is more to a component than just creating a file with the extension .cfc. There are some tags involved, too. Everything in a component is wrapped in the cfcomponent tag. These are its attributes:

  • Extends: When you're dealing with inheritance, the "extends" attribute specifies the name of the component that this component will inherit its properties and methods from. This is an optional attribute.
  • Output: The output attribute specifies whether the component body is allowed to generate output. If you set this value to yes, then everything inside the component, but not in a method, is processed as if it were inside a cfoutput tag of a standard template (I'll tell you shortly about component code that's not in a method). Methods will inherit this property, but it can be overridden at the function level. If you set this to no, then the component code outside of methods is processed as if inside a cfsilent tag. That is to say, all output is suppressed (more information about cfsilent is at livedocs.macromedia.com/coldfusion/6.1/htmldocs/tags-pc7.htm#wp1103549). If you omit this attribute, then the code is processed as standard CFML. It's rare and not recommended to output data from inside of a component, so I will set this attribute to no in the examples in this article.
  • DisplayName: ColdFusion Components are self-documenting. Attempting to browse directly to a CFC is intercepted by a component browser utility that displays the component documentation on the screen. The process of generating documentation in this manner is called introspection and the data displayed is called metadata. When you view the metadata of a compoment, the DisplayName attribute is listed next to the component's name. This is an optional attribute. It has no effect on functionality.
  • Hint: The hint attribute is another attribute that helps the CFC self-documenting feature. The text specified in the hint is displayed as part of the documentation. It's optional. It has no effect on functionality.
The interesting thing about the cfcomponent tag is that it is not necessarily needed in a cfc file. A cfc file is inherently a component, so we don't need to define it as such. In reality, the cfcomponent tag is almost always used, due to its attributes such as output and extends. If you really wanted to, you could use the cfcomponent tag in a cfm file to create a component.

Inside the cfcomponent tag you can define your component methods using the cffunction tag. Each component can have as many methods as you need. More information on cffunction can be found at livedocs.macromedia.com/coldfusion/6.1/htmldocs/tags-p43.htm#wp2852457. We also talked about functions in last month's column. These are the attributes to cffunction that are especially useful inside of CFCs:

  • Roles: The roles attribute is used to specify the roles that are allowed to access this function. This refers to the roles that are set when a user logs in using the ColdFusion cfloginuser tag. You can use this to control the users who can access individual component methods.
  • Access: The access attribute specifies the type of access a user must have to execute the function. The valid values for this are Private, Package, Public, and Remote. The default is Public, which means it can be executed by any local file. Private means only code inside the component can execute this function. Package means that only code inside the component package can execute it. A Package is all of the components in the same directory and subdirectories. Remote means it can be invoked remotely via Web services or Flash Remoting or (though rarely done) via URL GET or FORM POST operations.
  • Output: The output attribute on cffunction acts just like the output attribute on cfcomponent. If set to yes, then the body of the function will generate output. If set to no, then the body of the function will be treated as if it were inside a cfsilent block. In this article I'll set this to no, unless I'm trying to debug a function or if I'm creating a function whose sole purpose is to output data.
  • Displayname: Displayname is an optional attribute used only for display in the metadata of a component. Similar to the attribute of the cfcomponent tag, this attribute displays its value in parenthesis after the name of the function when viewing metadata and has no effect on performance.
  • Hint: The hint attribute is used to display comments or additional documentation in the component metadata. It is displayed under the function name as part of the metadata. It has no effect on functionality.
Other cffunction attributes, such as name and returntype still apply to functions inside a cfcomponent. The functions inside a component are often called methods, and the two terms can be used interchangeably: most developers will understand what you're talking about.

You may say: "I see that you mentioned something about code inside a component, but not inside a function. What can you tell me about that?" I'm glad you reminded me. The code in between cfcomponent tags, but not inside a cffunction block, is executed when you first create the component instance, but not when you make any subsequent calls on an existing instance. This is sometimes called "constructor" code. A constructor is an object-oriented programming (OOP)term that refers to a method that is executed when you create an object. A constructor is officially a method in OOP terminology, and since the CFC form of initialization is not a method, it is often called a pseudoconstructor.

Variables Inside a Component
There are two primary elements in a component: data and functionality. In the previous section we explored how to write the functionality. Here, you'll learn about the data. The data is stored in variables. You probably know all about variables in standard cfm templates. You can create them with cfset tags and they reside in different variable scopes, depending on the intended purpose of the variable. You can read a lot more about this in the first edition of this column (February '04).

Since you know all about variables, I'm going to jump right over the basics and go right into the scopes that exist inside a component:

  • This: This is a reference to everything public inside the component and can be thought of as the component's public scope. If you create a variable in the "this" scope, the variable can be accessed by anything that operates on the instance of the component. I don't usually use the "this" scope for variables for reasons you'll soon understand.
  • Variables: You'll recognize the variables scope from your work with cfm templates. In a component, the variables scope is used to hold private data. This data is sometimes called instance data.
  • Arguments: The arguments scope exists only inside a method, during the execution of a function. It contains all the arguments passed into the function (very similar to the "attributes" scope when creating custom tags).
  • Local function scope: The local function scope is an unnamed scope. All variables that you create with the "var" keyword using CFSET or CFSCRIPT exist in this scope.
  • Shared scopes: Inside a cfcomponent, you can access the shared scopes, such as application and session. Since the component is part of a request, request-based scopes such as URL, form, and request, are available to the component. Accessing these scopes is generally considered bad practice because it makes the code less reusable.
When developing components, I will use the "constructor" code to initialize variables in the components variables scope. I will create a number of methods to retrieve the private values (called getter methods because they only return a value) and methods to set the value of the private variables (called setter methods because they set a value).

Calling Components
There are a handful of different methods you can use to call components. I'm going to explain the one that I use most often. It's a two-step process, but is much more fun than country dancing. The first step is to create the component instance. The second step is to call various methods against the component. Component data will be persisted between component requests. Here is a sample component, entitled foo.cfc:


 <cfset variables.bar = " corner">

 <cffunction name="Getbar" access="public" returntype="string">
  <cfreturn variables.bar>

 <cffunction name="Setbar" access="public" returntype="boolean">
  <cfargument name="bar" type="string" required="Yes">
  <cfset variables.bar = arguments.bar>
  <Cfreturn true>


The foo component is very simple. It has one instance value, named bar. The bar variable is initialized to a string value "chunky".

To use the CFC you first need to create the instance of the component. You can use the cfobject tag or the createObject function to create the instance. Conceptually, both are similar. You can read about the createObject function at livedocs.macromedia.com/coldfusion/6.1/htmldocs/functi45.htm#wp4569859. I'll explain the cfobject tag in more detail. It has two attributes in relation to components:

  • Component: The component attribute specifies the location of the component, including the name of the file without the cfc. If they are in the same directory you can just use the component name.
  • Name: The name of the return variable that will contain the component instance.
More information about using cfobject to invoke components is located at livedocs.macromedia.com/coldfusion/6.1/htmldocs/tags-pb7.htm#wp2651979. This is a snippet of code to invoke our foo component:

<cfobject component="Foo" name="objFoo">

To invoke a method on the component, we use the cfinvoke tag. These are its attributes:

  • Component: The component attribute is used to specify the name of component instance. To reference an instance that is already created, you must put it in pound signs. If you are calling a single method of a CFC without creating an instance, you can enter the location of the CFC.
  • Method: The method attribute is used to specify the name of the method you want to execute.
  • ReturnVariable: The ReturnVariable attribute specifies the name of the variable that is populated with the return value.
  • ArgumentCollection: The argument collection attribute is used to specify the name of a structure that contains all arguments that the function requires. It is optional. You can also list arguments using name value pairs that correspond to the arguments in the function, or by using cfinvokeargument tags nested inside the cfinvoke block.
After creating our instance, we can use the cfinvoke tag to check the value of the bar instance variable:

<cfinvoke component="#objFoo#" method="getBar" returnvariable="variables.Out"/>

This code calls the GetBar method, putting the return variable in the out value and then outputting the value. You'll see that the Bar instance variable has not changed since we set it. We can change that using this line of code:

<cfinvoke component="#objFoo#" method="SetBar" bar="Main"/>

Rerun the previous segment after running the Set method and you'll see that the value has correctly changed.

Are CFCs Object-Oriented?
"So, Jeff," you say, "when I create a CFC it sounds like I'm creating an object. Isn't that object-oriented programming? I've heard that the use of CFCs is object-oriented. Isn't that true?" Again, I'm glad you asked. The answer is, quite indirectly, "sort of." There is no doubt that CFCs bring many object-oriented (OO) features into the CFML language. However, just because you are using CFCs does not mean you are programming in an OO way.

When we talk about object-oriented programming or traditional (procedural) programming, we're really talking about the approach taken to design an application. In ideal cases, this application design occurs before you sit down to write code. In CF5 and before, it was not as easy to implement an object-oriented design using ColdFusion. There is a group of custom tags called cfObjects that were used to apply OO design to ColdFusion. More info is available at http://cfobjects.sourceforge.net/. ColdFusion Components make the implementation of object-oriented designs much easier.

"So, then," you ask, "CFCs are object oriented, right?" They can be, yes. But, even if you are not using an object-oriented design you can still make use of CFCs. Instead of creating classes for an OO design, you can use CFCs to create Abstract Data Types (ADTs). In simple terms, an ADT is a user-defined data type. Just like classes in OO design, Abstract Data Types provide a way to encapsulate data and the functionality to operate on that data into one component. ADTs generally do not make use of OO specific concepts, such as inheritance or polymorphism.

ColdFusion Components are a powerful tool in the toolbox of any ColdFusion developer. They provide advanced encapsulation, so that you can more easily write reusable components and speed the development of future applications. They also open the door to the use of Web services and Flash Remoting. After reading this article, you should understand all the basics of creating CFCs. Next month, I'm going to show you how I like to use CFCs and I'll step you through the process of creating a reusable component.

More Stories By Jeffry Houser

Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

Comments (0)

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.

@ThingsExpo Stories
SYS-CON Events announced today that Technologic Systems Inc., an embedded systems solutions company, will exhibit at SYS-CON's @ThingsExpo, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Technologic Systems is an embedded systems company with headquarters in Fountain Hills, Arizona. They have been in business for 32 years, helping more than 8,000 OEM customers and building over a hundred COTS products that have never been discontinued. Technologic Systems’ pr...
SYS-CON Events announced today that Auditwerx will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Auditwerx specializes in SOC 1, SOC 2, and SOC 3 attestation services throughout the U.S. and Canada. As a division of Carr, Riggs & Ingram (CRI), one of the top 20 largest CPA firms nationally, you can expect the resources, skills, and experience of a much larger firm combined with the accessibility and attent...
SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From ...
SYS-CON Events announced today that HTBase will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. HTBase (Gartner 2016 Cool Vendor) delivers a Composable IT infrastructure solution architected for agility and increased efficiency. It turns compute, storage, and fabric into fluid pools of resources that are easily composed and re-composed to meet each application’s needs. With HTBase, companies can quickly prov...
SYS-CON Events announced today that Loom Systems will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2015, Loom Systems delivers an advanced AI solution to predict and prevent problems in the digital business. Loom stands alone in the industry as an AI analysis platform requiring no prior math knowledge from operators, leveraging the existing staff to succeed in the digital era. With offices in S...
Buzzword alert: Microservices and IoT at a DevOps conference? What could possibly go wrong? In this Power Panel at DevOps Summit, moderated by Jason Bloomberg, the leading expert on architecting agility for the enterprise and president of Intellyx, panelists peeled away the buzz and discuss the important architectural principles behind implementing IoT solutions for the enterprise. As remote IoT devices and sensors become increasingly intelligent, they become part of our distributed cloud enviro...
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
SYS-CON Events announced today that Infranics will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Since 2000, Infranics has developed SysMaster Suite, which is required for the stable and efficient management of ICT infrastructure. The ICT management solution developed and provided by Infranics continues to add intelligence to the ICT infrastructure through the IMC (Infra Management Cycle) based on mathemat...
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and management into a ...
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), will provide an overview of various initiatives to certifiy the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldw...
In his General Session at 16th Cloud Expo, David Shacochis, host of The Hybrid IT Files podcast and Vice President at CenturyLink, investigated three key trends of the “gigabit economy" though the story of a Fortune 500 communications company in transformation. Narrating how multi-modal hybrid IT, service automation, and agile delivery all intersect, he will cover the role of storytelling and empathy in achieving strategic alignment between the enterprise and its information technology.
Microservices are a very exciting architectural approach that many organizations are looking to as a way to accelerate innovation. Microservices promise to allow teams to move away from monolithic "ball of mud" systems, but the reality is that, in the vast majority of organizations, different projects and technologies will continue to be developed at different speeds. How to handle the dependencies between these disparate systems with different iteration cycles? Consider the "canoncial problem" ...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
Keeping pace with advancements in software delivery processes and tooling is taxing even for the most proficient organizations. Point tools, platforms, open source and the increasing adoption of private and public cloud services requires strong engineering rigor - all in the face of developer demands to use the tools of choice. As Agile has settled in as a mainstream practice, now DevOps has emerged as the next wave to improve software delivery speed and output. To make DevOps work, organization...
My team embarked on building a data lake for our sales and marketing data to better understand customer journeys. This required building a hybrid data pipeline to connect our cloud CRM with the new Hadoop Data Lake. One challenge is that IT was not in a position to provide support until we proved value and marketing did not have the experience, so we embarked on the journey ourselves within the product marketing team for our line of business within Progress. In his session at @BigDataExpo, Sum...
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
What sort of WebRTC based applications can we expect to see over the next year and beyond? One way to predict development trends is to see what sorts of applications startups are building. In his session at @ThingsExpo, Arin Sime, founder of WebRTC.ventures, will discuss the current and likely future trends in WebRTC application development based on real requests for custom applications from real customers, as well as other public sources of information,
In his General Session at 17th Cloud Expo, Bruce Swann, Senior Product Marketing Manager for Adobe Campaign, explored the key ingredients of cross-channel marketing in a digital world. Learn how the Adobe Marketing Cloud can help marketers embrace opportunities for personalized, relevant and real-time customer engagement across offline (direct mail, point of sale, call center) and digital (email, website, SMS, mobile apps, social networks, connected objects).