|By Ben Forta||
|October 15, 2003 04:35 PM EDT||
ColdFusion developers rely on session state management and the SESSION scope extensively. But as applications grow in complexity, so do the number of SESSION variables, and the risk of overwriting or misusing them. It need not be that way; with a little work (and ColdFusion Components), SESSION use can be clean, simple, and highly organized.
When Session Data Proliferates
First, an introduction. The Web is stateless. Or put in terms that actually mean something, every request on the Web stands on its own two feet. The data received by a form submission, for example, is only available in the receiving page and not to subsequent requests. Or, user credentials specified at login are not kept until logout. And similarly, items put in a shopping cart won't still be in the cart at checkout time.
But wait a minute, those statements can't be true, can they? After all, we've all put items in shopping carts and then checked out, and we've all logged in to sites that remembered us until logout, haven't we? If the Web is stateless, how is that data maintained? That's the job of session state management, a mechanism that creates the illusion of state in a stateless world.
Data to be maintained between requests is stored on the server, along with an id that designates the client that the data belongs to. That id is sent back and forth with each and every request, so that the server can associate the maintained data and give the illusion of persistent data. In ColdFusion all this is accomplished using SESSION variables. Developers simply refer to variables like #SESSION.Firstname# and ColdFusion takes care of all the details (setting and receiving session identifiers, maintaining the SESSION data, and ensuring that the correct data is used when referring to variables with the SESSION scope).
Okay, end of introduction.
So you need to track session information, great. The first thing you do is set SESSIONMANAGEMNT="yes" in your <CFAPPLICATION> tag (which makes a lot of sense; after all, you can't use the SESSION scope without having first instructed ColdFusion to enable that functionality. Once enabled you are free to save any data within SESSION. For example, a simple variable:
or a more complex data type:
or even queries:
WHERE user_id = #FORM.user_id#
There is no limit to what can be stored
in the SESSION scope. That's a good
thing, but it's also a liability. Why?
Consider the following:
This is just the tip of the iceberg. The key here is that because SESSION variables are so easy to create and use, their use can quickly get out of hand unless some semblance of structure is imposed.
The Basics of Encapsulation
The word encapsulation is one of those terms that means lots of different things and usually ends up being misused most of the time. But at its simplest, encapsulation is a technique by which applications are separated into parts so that code need not know the inner workings of things it doesn't need to know.
For example, stored procedures are one of the best known forms of encapsulation. A stored procedure contains one or more database instructions in the form of SQL statements, but all that is hidden from the stored procedure user who simply makes a call to obtain data or to perform some other operation. What happens within the stored procedure is not important, what is important is that it does what it's supposed to do, it just works.
ColdFusion Custom Tags (or rather, well-written ColdFusion Custom Tags) offer another form of encapsulation. A tag is invoked to perform an operation, the details of which are concealed within the tag.
Encapsulation thus does several things:
I'm using the term encapsulation a little more loosely than most object-oriented developers would like, but having said that, this is indeed what encapsulation is all about. (Note: This idea was explained in detail in CFDJ, Volume 4, issue 10.)
ColdFusion Components and Encapsulation
ColdFusion Components (CFCs for short), first introduced in ColdFusion MX, are a way to create reusable objects in ColdFusion. Although not objects in the purest sense, they do provide basic object functionality wrapped within the simplicity that is uniquely CFML. (Note: ColdFusion Components were introduced in detail in a two-part column that appeared in CFDJ, Volume 4, issues 6 & 7.)
Two of the most important aspects of CFCs is that they can store data internally, and they can persist. Let me explain. Within every CFC is a special scope named THIS. THIS contains some default data, but it can also be used to store data of your own. For example, the following method accepts two arguments (first and last name) and then saves them into the THIS scope:
To invoke this method you could use the following code (assuming the previous method was saved in a file named user.cfc):
This next method returns a string made up of the saved first and last name:
<CFRETURN THIS.NameFirst & " " &
So, SetName saves the name and GetName retrieves it, so the following code should save my name and return it as a string:
If you were to execute this code, however, you would throw an error. The SetName call will work, but GetName will complain that THIS.NameFirst and THIS.NameLast do not exist. Why? After all, they were just set in SetName?
The problem with the above invocation is that the user component is being invoked twice, two separate invocations that have nothing to do with each other. Each <CFINVOKE> loads the component, invokes the appropriate method, and then unloads the components. So when GetName is executed there is no NameFirst and NameLast in THIS; those were in the previously invoked instance.
The solution? Persistence. Aside from being a type of file, a CFC is a ColdFusion data type, an object. <CFINVOKE>, as used above, loads the object, uses it, and then unloads it. But those steps can be separated. Look at this example:
Here the component is being loaded as an object (which it actually is). The <CFOBJECT> instantiates (creates an instance of) the user object, but does not invoke any method. Rather, it stores the object in a named variable. <CFINVOKE> then invokes the previously loaded object; notice that the value passed to COMPONENT is the object (as opposed to the name of the CFC). Once an object is loaded it can be used multiple times, and as it is the same object being used over and over, all invocations share the same object and thus the same internal THIS scope.
Here's a corrected version of the code to set and get the user name:
<CFOBJECT> instantiates the object, SetName stores the values into THIS, and GetName returns it (possibly to be displayed).
This can also be accomplished using object style invocation. For example, the object instantiation could be performed using:
and the GetName could be executed as:
or used directly for display as:
So, components are objects and can persist. The examples thus far loaded the object as local variables (type VARIABLES, the default variable type). But other scopes may be used too. Components may be loaded into REQUEST, for example:
<CFOBJECT COMPONENT="user" NAME="REQUEST.userObj">
and components may even be loaded into persistent scopes like SESSION:
<CFSET SESSION.user=CreateObject("component", "user")>
Which brings us back to session state management. Instead of defining and accessing all sorts of SESSION variables throughout your application, you could define just one, an object (an instantiated ColdFusion Component). If your application uses user data you may want to create a user.cfc, which would contain all user information (including obtaining information from underlying databases). To check if a user has logged in you'd use code like this:
<CFIF NOT IsDefined("SESSION.user")>
... redirect to login page ...
The login page would authenticate the user (if needed) and then create an instance of the user object in the user's SESSION scope:
<CFOBJECT COMPONENT="user" NAME="SESSION.user">
You may then want to initialize the object so as to populate the internal THIS with any needed information (user name, color preferences, language choices, and so on). Perhaps you'd simply pass the user id to an initialization method immediately after object creation:
Init() should probably return a true or false flag (indicating whether or not the initialization was successful), and within the CFC you'll probably want each method to ensure that Init() was called before begin executed, but that is all internal to the CFC.
What about user logout? Simple; when a user logs out you'd kill SESSION. user like this:
<CFSET StructDelete(SESSION, "user")>
so that on a subsequent request the login and initialization process would restart.
With user.cfc you can do anything, so perhaps you'd have methods like these:
And this goes beyond user processing. Consider a shopping cart example. Shopping carts are stored in SESSION variables, but instead of storing arrays or structures or arrays of structures of whatever in SESSION and accessing them directly, you'd create a cart component. To start shopping you'd create an instance of the cart:
<CFOBJECT COMPONENT="cart" NAME="SESSION.cart">
When an item is to be added you'd call the appropriate method:
Other methods would update or remove items, and perhaps a list method would return a query (a ColdFusion query created within the CFC using the QueryNew() function) for displaying or processing. There is no limit to what you can do within a CFC, and your CFC code can evolve and adapt independent of any calling code.
ColdFusion Components are objects. CFCs facilitate the encapsulation of data and logic, and they can be made to persist if needed. The combination of these two features makes CFCs perfect for managing session state. With minimal work the techniques described here can be used in any application, and doing so will both simplify and improve your code.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
Nov. 23, 2014 07:30 PM EST Reads: 1,672
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nov. 23, 2014 12:00 PM EST Reads: 1,607
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
Nov. 23, 2014 07:45 AM EST Reads: 1,457
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Nov. 22, 2014 10:00 PM EST Reads: 1,341
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
Nov. 22, 2014 05:30 PM EST Reads: 1,439
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
Nov. 22, 2014 05:30 PM EST Reads: 1,287
ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ -- IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...
Nov. 22, 2014 05:30 PM EST Reads: 1,452
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Nov. 21, 2014 09:15 PM EST Reads: 1,362
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
Nov. 21, 2014 08:00 PM EST Reads: 1,377
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
Nov. 21, 2014 08:00 PM EST Reads: 1,429
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nov. 21, 2014 07:00 PM EST Reads: 1,285
Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
Nov. 20, 2014 09:15 PM EST Reads: 1,373
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
Nov. 20, 2014 06:00 PM EST Reads: 1,333
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
Nov. 20, 2014 04:45 PM EST Reads: 1,124
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
Nov. 20, 2014 01:00 PM EST Reads: 1,580
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
Nov. 20, 2014 12:30 PM EST Reads: 1,790
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
Nov. 18, 2014 09:00 PM EST Reads: 2,015
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
Nov. 18, 2014 08:15 PM EST Reads: 1,566
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
Nov. 18, 2014 01:30 PM EST Reads: 2,007
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world. The next @ThingsExpo will take place November 4-6, 2014, at the Santa Clara Convention Center, in Santa Clara, California. Since its launch in 2008, Cloud Expo TV commercials have been aired and CNBC, Fox News Network, and Bloomberg TV. Please enjoy our 2014 commercial.
Nov. 13, 2014 05:00 AM EST Reads: 3,543