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)

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
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
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.
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...
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...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
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...