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, Adobe Flex

ColdFusion: Article

Using Objects in Your Adobe ColdFusion MX Applications

Developing reusable, maintainable code

As ColdFusion has become a leading choice for large-scale quick-to-market application development, new CF server releases have been adapted to make it possible to integrate object classes into your Web applications. Since ColdFusion MX, developers have been able to architect applications using CFCs.

CFCs have enabled us to develop object classes, extend classes, and allow classes to inherit properties and methods from other CFCs in very short order, giving the CF development community a way to approach ColdFusion from a more object-oriented style. Using this line of thinking during your architectural process lets the development team quickly build applications that are highly reusable and maintainable.

The reader is expected to have a solid grasp of the ColdFusion MX programming language. A basic understanding of core object-oriented principles will help with concept comprehension, but isn't required.

Objects Defined
In object-oriented programming, an object is defined as "a container of related data (properties), and the methods that control inserting and retrieving that data. This process is termed encapsulation. Encapsulation, one of the three key properties of object-oriented programming (OOP), is the process by which access to data or procedures is limited to a specified interface. An object is an instance of a class, which is a model instantiated to create a logical entity that handles storage and management of data (the object). The object can then be used as a single entity throughout your code."

To simplify, an object is a single instance of a class that contains data related to the object, and the methods that let data be set or retrieved from the object instance. So how do objects help us achieve our goal of developing reusable, maintainable code? Here's a basic example: in CF5 (non-object-oriented), a developer would query the data persistence layer to return a record set. Each record in the set could, in turn, relate to an object record persisted in the database. The developer would loop over the record set and output each row with very little control. Basically, the record set was displayed in the order it was returned from the original query. If a record in the set had to be changed, the developer would have to write an update statement and supply property values one-by-one for that specific row. The initial query would then need to be rerun to get the new values before the record set was displayed again. There is very little control over each record in the set. With the use of objects in CFMX, a developer can create a collection of objects (discussed below), and populate them from a single query. Each object in the collection can now be retrieved as a single entity, and the developer can retrieve or modify the values of each entity through accessor methods. He can then persist a single object from the collection (which may even self-validate) or the entire collection and keep using the updated object in the request (we don't need to re-query since the object or collection already contains the updated properties). We can also persist the object or collection in a CF scope, such as the session scope, and use the object indefinitely throughout our application across requests. This is just one example as objects have many advantages over standard record sets.

Creating a Class in ColdFusion MX
Now that we have a basic understanding as to why we would implement objects in ColdFusion, we'll explain creating an object class. A class is nothing more than a standard ColdFusion component that contains private variables to store object properties, an init() method so the class can be instantiated, and accessor methods (sometimes referred to as getters and setters). Below I'll create a Foo class that contains two properties: fooName and fooDescription. In a real-world application, we may use an Employee class that contains firstName, lastName, and emailAddress. Any ColdFusion class should begin with a <cfcomponent> tag:

<cfcomponent hint="I am the Foo class.">

Next, we define the object properties. Since in object-oriented programming we want to encapsulate the object properties, we use the ColdFusion VARIABLES scope to store the variables referring to the properties . If we used the THIS scope instead, the properties would be available directly to a developer using the object. We want to require the developer to use the defined accessor methods to affect any object property:

<cfset variables.fooName = "" />
<cfset variables.fooDescription = "" />

Every class should contain an init() method. This method returns an initialized instance of the class (object). (See below.) Any default properties we want to set can also be included in the init() method. We could also pass in arguments to this method to use during object instantiation.

<cffunction name="init" access="public" returnType="Foo" output="false" hint="I instantiate Foo">
<cfset variables.fooDescription = "none" />
<cfreturn this />

Now that we have our properties encapsulated and have created a method that lets us instantiate an object of the class, we need to define the accessor methods that will let the developer interact with the private class properties. There are two types of accessor methods: one type sets a property value and one type returns a property value. These accessor methods are commonly referred to as "getters" and "setters." The class will define one getter method and one setter method per property (See Listing 1.). In our Foo example, both fooName and fooDescription are CF string types, so our getter return types and setter arguments are both strings.

The last step is to close our ColdFusion component definition:


Instantiating an Object in ColdFusion MX
To create a ColdFusion object, we have to create an instance of our class. This instance is the physical representation of the class and lets us interact with the object. There are a few ways to instantiate an object. I'll be discussing createObject(). As a reference, you may want to check the Adobe Livedocs for <cfobject> and <cfinvoke>.

For the current example, Foo.cfc (the Foo class created above) resides in a directory off the Webroot named cfc. When referring to Foo.cfc, we use the dot notation "cfc.Foo." This tells ColdFusion where the file is located. In the same call, I've included the init() method so the object that's returned and set equal to foo is a fully instantiated class (see below). When running createObject() alone, only code that's outside the defined methods is evaluated.

foo = createObject("component", "cfc.Foo").init();
<cfset foo = createObject("component", "cfc.Foo").init() />

Our object is now instantiated and can be affected through the use of the accessor methods. To learn more about the object, <cfdump> foo to see the object's structure. Note that you can't see any of the encapsulated properties in the variables scope. The accessor methods are used as displayed below.

// instatiate foo
foo = createObject("component", "cfc.Foo");
// set the fooName property in the object
<!--- display fooName --->

Note that the accessor methods can also be used just as easily without using <cfscript> (<cfset foo.setFooName("myFoo") />).

More Stories By Nic Tunney

Nicholas Tunney is a Macromedia Certified ColdFusion developer, and has been programming ColdFusion for over 7 years. He is currently Senior Software Architect for AboutWeb, a consulting firm located in Rockville, Maryland. To learn more about using objects in ColdFusion, visit Nic's Blog at http://www.nictunney.com.

Comments (3) 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
SYS-CON India News Desk 06/23/06 01:32:32 PM EDT

As ColdFusion has become a leading choice for large-scale quick-to-market application development, new CF server releases have been adapted to make it possible to integrate object classes into your Web applications. Since ColdFusion MX, developers have been able to architect applications using CFCs.

SYS-CON Italy News Desk 06/23/06 09:03:57 AM EDT

As ColdFusion has become a leading choice for large-scale quick-to-market application development, new CF server releases have been adapted to make it possible to integrate object classes into your Web applications. Since ColdFusion MX, developers have been able to architect applications using CFCs.

J Buda 06/22/06 10:30:30 AM EDT

I thought that was a good article and though i had finally got my head round oop in cf.

However i have a question. Why are we initialising the widget in the foo object? I want to populate the widgetName in the widget cfc, but am getting that the widget method has not been passed into the setWidget in the foo object.
Im trying this....cfset foo.setWidget().setWidgetName('bob')


IoT & Smart Cities Stories
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...
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...
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...
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 ...
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.
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 ...
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...