|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 Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Avere delivers a more modern architectural approach to storage that doesn’t require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbuilding of data centers ...
Feb. 10, 2016 12:45 PM EST
SYS-CON Events announced today that Commvault, a global leader in enterprise data protection and information management, has been named “Bronze Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Commvault is a leading provider of data protection and information management...
Feb. 10, 2016 12:15 PM EST Reads: 420
SYS-CON Events announced today that VAI, a leading ERP software provider, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. VAI (Vormittag Associates, Inc.) is a leading independent mid-market ERP software developer renowned for its flexible solutions and ability to automate critical business functions for the distribution, manufacturing, specialty retail and service sectors. An IBM Premier Business Part...
Feb. 10, 2016 12:00 PM EST Reads: 612
With an estimated 50 billion devices connected to the Internet by 2020, several industries will begin to expand their capabilities for retaining end point data at the edge to better utilize the range of data types and sheer volume of M2M data generated by the Internet of Things. In his session at @ThingsExpo, Don DeLoach, CEO and President of Infobright, will discuss the infrastructures businesses will need to implement to handle this explosion of data by providing specific use cases for filte...
Feb. 10, 2016 11:00 AM EST Reads: 181
Cognitive Computing is becoming the foundation for a new generation of solutions that have the potential to transform business. Unlike traditional approaches to building solutions, a cognitive computing approach allows the data to help determine the way applications are designed. This contrasts with conventional software development that begins with defining logic based on the current way a business operates. In her session at 18th Cloud Expo, Judith S. Hurwitz, President and CEO of Hurwitz & ...
Feb. 10, 2016 10:45 AM EST Reads: 244
Fortunately, meaningful and tangible business cases for IoT are plentiful in a broad array of industries and vertical markets. These range from simple warranty cost reduction for capital intensive assets, to minimizing downtime for vital business tools, to creating feedback loops improving product design, to improving and enhancing enterprise customer experiences. All of these business cases, which will be briefly explored in this session, hinge on cost effectively extracting relevant data from ...
Feb. 10, 2016 10:45 AM EST
SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies adopt disruptive technologies to optimize revenue-generating systems, has been named “Bronze Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Founded in 1997, Pythian is a global IT services company that helps companies compete by adopting disruptive technologies such as cloud, Big Data, advanced analytics, and DevO...
Feb. 10, 2016 10:30 AM EST Reads: 212
Companies can harness IoT and predictive analytics to sustain business continuity; predict and manage site performance during emergencies; minimize expensive reactive maintenance; and forecast equipment and maintenance budgets and expenditures. Providing cost-effective, uninterrupted service is challenging, particularly for organizations with geographically dispersed operations.
Feb. 10, 2016 10:04 AM EST
With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts...
Feb. 10, 2016 09:00 AM EST Reads: 381
As enterprises work to take advantage of Big Data technologies, they frequently become distracted by product-level decisions. In most new Big Data builds this approach is completely counter-productive: it presupposes tools that may not be a fit for development teams, forces IT to take on the burden of evaluating and maintaining unfamiliar technology, and represents a major up-front expense. In his session at @BigDataExpo at @ThingsExpo, Andrew Warfield, CTO and Co-Founder of Coho Data, will dis...
Feb. 10, 2016 09:00 AM EST Reads: 181
SYS-CON Events announced today that iDevices®, the preeminent brand in the connected home industry, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. iDevices, the preeminent brand in the connected home industry, has a growing line of HomeKit-enabled products available at the largest retailers worldwide. Through the “Designed with iDevices” co-development program and its custom-built IoT Cloud Infrastruc...
Feb. 10, 2016 08:00 AM EST
Eighty percent of a data scientist’s time is spent gathering and cleaning up data, and 80% of all data is unstructured and almost never analyzed. Cognitive computing, in combination with Big Data, is changing the equation by creating data reservoirs and using natural language processing to enable analysis of unstructured data sources. This is impacting every aspect of the analytics profession from how data is mined (and by whom) to how it is delivered. This is not some futuristic vision: it's ha...
Feb. 10, 2016 07:45 AM EST Reads: 435
Silver Spring Networks, Inc. (NYSE: SSNI) extended its Internet of Things technology platform with performance enhancements to Gen5 – its fifth generation critical infrastructure networking platform. Already delivering nearly 23 million devices on five continents as one of the leading networking providers in the market, Silver Spring announced it is doubling the maximum speed of its Gen5 network to up to 2.4 Mbps, increasing computational performance by 10x, supporting simultaneous mesh communic...
Feb. 10, 2016 07:00 AM EST
The cloud promises new levels of agility and cost-savings for Big Data, data warehousing and analytics. But it’s challenging to understand all the options – from IaaS and PaaS to newer services like HaaS (Hadoop as a Service) and BDaaS (Big Data as a Service). In her session at @BigDataExpo at @ThingsExpo, Hannah Smalltree, a director at Cazena, will provide an educational overview of emerging “as-a-service” options for Big Data in the cloud. This is critical background for IT and data profes...
Feb. 10, 2016 12:45 AM EST Reads: 199
SYS-CON Events announced today that Men & Mice, the leading global provider of DNS, DHCP and IP address management overlay solutions, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. The Men & Mice Suite overlay solution is already known for its powerful application in heterogeneous operating environments, enabling enterprises to scale without fuss. Building on a solid range of diverse platform support,...
Feb. 10, 2016 12:00 AM EST Reads: 208
SYS-CON Events announced today that Alert Logic, Inc., the leading provider of Security-as-a-Service solutions for the cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Alert Logic, Inc., provides Security-as-a-Service for on-premises, cloud, and hybrid infrastructures, delivering deep security insight and continuous protection for customers at a lower cost than traditional security solutions. Ful...
Feb. 9, 2016 02:15 PM EST Reads: 408
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 ad...
Feb. 9, 2016 01:15 PM EST Reads: 389
One of the bewildering things about DevOps is integrating the massive toolchain including the dozens of new tools that seem to crop up every year. Part of DevOps is Continuous Delivery and having a complex toolchain can add additional integration and setup to your developer environment. In his session at @DevOpsSummit at 18th Cloud Expo, Miko Matsumura, Chief Marketing Officer of Gradle Inc., will discuss which tools to use in a developer stack, how to provision the toolchain to minimize onboa...
Feb. 9, 2016 07:45 AM EST Reads: 102
SYS-CON Events announced today that Fusion, a leading provider of cloud services, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Fusion, a leading provider of integrated cloud solutions to small, medium and large businesses, is the industry's single source for the cloud. Fusion's advanced, proprietary cloud service platform enables the integration of leading edge solutions in the cloud, including clou...
Feb. 6, 2016 03:30 PM EST Reads: 761
Most people haven’t heard the word, “gamification,” even though they probably, and perhaps unwittingly, participate in it every day. Gamification is “the process of adding games or game-like elements to something (as a task) so as to encourage participation.” Further, gamification is about bringing game mechanics – rules, constructs, processes, and methods – into the real world in an effort to engage people. In his session at @ThingsExpo, Robert Endo, owner and engagement manager of Intrepid D...
Feb. 5, 2016 09:00 PM EST Reads: 821