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)

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
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...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.