Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News

SYS-CON.TV
Cloud Expo & Virtualization 2009 East
PLATINUM SPONSORS:
IBM
Smarter Business Solutions Through Dynamic Infrastructure
IBM
Smarter Insights: How the CIO Becomes a Hero Again
Microsoft
Windows Azure
GOLD SPONSORS:
Appsense
Why VDI?
CA
Maximizing the Business Value of Virtualization in Enterprise and Cloud Computing Environments
ExactTarget
Messaging in the Cloud - Email, SMS and Voice
Freedom OSS
Stairway to the Cloud
Sun
Sun's Incubation Platform: Helping Startups Serve the Enterprise
POWER PANELS:
Cloud Computing & Enterprise IT: Cost & Operational Benefits
How and Why is a Flexible IT Infrastructure the Key To the Future?
Click For 2008 West
Event Webcasts
Creating a Component to Help You Collect Addresses
Squaring away address fields

Last month I introduced ColdFusion Components in this column. I wrote about the CFC file extension, the tags that make up components (cfcomponent and cffunction), how to create a component, and how to call methods on that component instance.

This month, I'll take you step-by-step through the process of creating a component that you can reuse in your own development. I'd be willing to bet that somewhere in your development adventures you've needed to collect an address from your users. Maybe you needed a billing address when you collected credit card information, or a shipping address when you sold a product through an e-commerce store. Perhaps you needed to collect a home address and a work address for the address book on your company's intranet. In this article, we'll create a standard component that you can use in all of these cases.

The Database Design
Before we can start writing code, we need to decide what type of data we want to store. A typical U.S.-based address will probably contain a street address, city, state, and zip. If you are dealing with international information, you may also want to store a country. Additional information might be a phone or fax number. You may want to store a name with your address information, although I usually have that information stored in a separate user table, so it's left out of this example (see Figure 1).

I added an AddressID field to the address table. This field is used as a primary key. When future tables or code reference an address they can do so using the primary key.

The street address is separated into two fields, Address1and Address2. This might be used in cases where the user needs one line for a street and house number, and a second line for an apartment number. State data is relegated to a separate table and referenced using a foreign key, StateID. I also added some date fields including DateCreated, TimeCreated, DateModified, and TimeModified. I add these fields to most tables, and will use them for reporting purposes.

Creating the Component
The first thing that we need to do is to set the instance variables of our component. I will set some initialization code in the pseudoconstructor area of the component. You may remember from last month that constructor code inside a component, but not inside a cffunction tag, is often called pseudoconstructor code. This code is executed every time an instance of the component is created (see Listing 1).

Integer fields, such as IDs, are initialized to zero. Text fields are initialized to empty strings. I initialized the date and time fields to empty strings, although in some cases I have initialized them to the current day or time. The instance data is placed in the variables scope, which means it is private to the component. All the instance data is placed in a structure inside the variables scope, which I called instance. This is so you can easily dump (using the cfdump tag) all the instance variables without having to display all the extraneous component information that would be displayed had you just dumped the variables scope.

The instance data is used to represent the database fields in the address table. It also contains the state data from the state table, such as state and state abbreviation. This data will probably be used primarily for display purposes in our application; when we update the address table, we'll only need the ID field.

You'll need a way to access the data from outside the component, since it is internal to the component. You can provide this through the use of getter and setter methods. A getter method is one that will get the value of a component variable. A setter method is one that will set the value of a component variable. Most of your getter and setter methods will be similar to each other, so I'll only give a simple example here. See Listing 2 for the get method for the address 1 variable

The name is GetAddress1, and the method is public. The return value is a string. The method body has a single line, which returns the value of the address1 instance variable. The set method is shown in Listing 3.

The name of this method is SetAddress1. Its access is public. The return type is a Boolean value. The method will return true if the set is a success, and false otherwise. Since this simple method does not contain any additional error checking, it will always return true (I'm making the assumption that the cfset will not fail).You could institute more complex error checking and have the method return false on failure. As an example, you may want to do this if a zip code has too few or too many characters. A single string argument is accepted for this method. The body consists of a cfset and a return.

Most of the get and set methods are simple, like the Address1 methods I just explained. One deviation is the StateID method. In reality, we could get by with just the StateID method, since that's the only field inside the address table. However, the state name and state abbreviation fields are included as a convenience to the developer. Listing 4 shows how the SetStateID method will retrieve this information.

This method accepts two arguments, the ID of the state and the name of the data source. It uses a query to retrieve the state data based on the ID passed into the function. Instead of just setting a single piece of data, it sets the state ID, the state name, and the state abbreviation. This method is an example of when more error checking might be beneficial. For instance, if nothing is returned from the query we could return false, or if the query failed for some reason we could return false.

Init and Commit Methods
A component's usefulness may be limited if it only has getter and setter methods. In our address component, we are going to add two additional methods. The first is an init method. The init method can be used to load data from the database and populate the instance data. The second method we are going to add is a commit method. The commit method will either create or update a database with the instance data of the component. Listing 5 shows the init method.

It accepts two arguments, the AddressID and the DSN. The AddressID is the primary key of the address record in the database. The DSN is the data source that refers to the database. It creates the name of the query as a local function variable using the var keyword. Then the code queries the database to retrieve the address information. The instance variables are set based on the query data and the function returns a Boolean true value.

The commit method is designed to update the information in the database. The code can be seen in Listing 6.

The method accepts the data source name (DSN) as the only argument. It checks the AddressID instance variable to see if we need to update the database or insert a new record. If the AddressID is 0, then we are dealing with new data. If the AddressID is not zero, then we can update that record in the database. If we create the new record, the AddressID is set. An SQL Server-specific method is used to retrieve the most up-to-date ID.

Using the Component
Now that you've created the component, how do you use it? Let's suppose you are creating a user component. The user component contains information about your users including their name, access levels, a home address, and a work address. How would I use the address component to create the home and work address? First, I'd initialize them in the constructor code using something like this:


<cfobject component="address" name="variables.instance.WorkAddress">
<cfobject component="address" name="variables.instance.HomeAddress">

I would add get and set methods, similar to Listing 7. For the set method, the address component initialization would be handled outside of the user method, and the component would be passed into the method as a variable. The argument type is the name of the address component, address.

To manipulate the address components through the user component you can use code like this:


UserComponentInstance.GetWorkAddress().GetAddress1()

Conclusion
This article should help you with the steps of building modular code. Components allow you to create the building blocks of an application. Over time, you'll develop a library of different components for different purposes, and then creating applications is just a matter of referencing your previously created jobs. As you start to develop a library of these components eventually your development will become quicker since you won't start every application from scratch.

About 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.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Latest Cloud Developer Stories
Can you bring services from the cloud to your customers faster and have them adopt it with ease of use or bring the power of bundled services to the fingertips of your clients without creating new rigid ‘apps stove pipes'? Do you want to prevent your business running away to publ...
OCZ Technology Group, a provider of high-performance solid-state drives (SSDs) for computing devices and systems, on Tuesday announced the Z-Drive R4 CloudServ PCI Express (PCIe) flash storage solution, designed to accelerate cloud computing applications and reduce operating expe...
Many organizations have embraced, or are considering, the benefits of cloud computing – speed, flexibility, increased expertise, shared workload, reduced costs, etc. The benefits are many – but so are the risks. What are the threats to cloud security? Which parties assume respons...
In August 2011, SHI Enterprise Solutions (ESS) division launched the SHI Cloud, offering reliable and cost-effective industrial-grade cloud computing platforms. That same division achieved an 82 percent increase in revenue over 2010.
SoftLayer Technologies on Tuesday announced the immediate worldwide availability of SoftLayer Object Storage, a redundant and highly scalable cloud storage service that allows users to easily store, search and retrieve data across the Internet, with optional CDN connectivity, or ...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE