Welcome!

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.

Prerequisites:
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 />
</cffunction>

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:

</cfcomponent>

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.

<cfscript>
foo = createObject("component", "cfc.Foo").init();
</cfscript>
[OR]
<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.

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

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')

Thanks

@ThingsExpo Stories
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
CloudEXPO | 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 All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DXWorldEXPO | CloudEXPO 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.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
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...