Follow-up on Session Variables vs. Hidden Inputs

A few people posted some very good comments to yesterday’s post on session variables versus hidden inputs. I want to highlight two very import points that were made.

  1. Put data in structs, and put the structs in users’ sessions. Rather than putting dozens of name/value pairs directly in users’ sessions, consider putting them all in a struct, and putting the struct in the session instead. This will help you avoid inadvertently stomping on existing name/value pairs, and makes it easier to clean up should you decide to clear the struct. It’s the same idea behind creating directories on your computer and organizing files logically and hierarchically rather than putting them all in a single directory where they are difficult to manage and you are likely to run into naming conflicts.
  2. CFC instances fit nicely in sessions. Even better than putting data in structs and putting structs in sessions is putting data in components and putting components in sessions. Why is it better? Think of a component as being a struct with optional logic. In addition to simple properties (essentially name/value pairs), you can add logic and functionality. For instance, I’m currently working on an application that creates a user component and puts it in all users’ sessions once they have successfully authenticated. The component has get and set functions for all the properties of a user, including ID, name, encrypted password, last login date, etc. So far, a struct would have worked fine, however I also wanted a property for the user’s current IP address, so inside of the getIpAddress function, I have logic to extract the user’s IP address out of the request (with Flash Remoting, you want to get the user’s IP address from the request because the CGI variable does not get properly populated). By using a component rather than a struct, not only am I able to add logic for functionality that I need now, but I have a good hook for extending the component’s functionality in the future. For instance, I’m considering adding a toString function, or a getUserHash which would return a string that uniquely identifies a particular user.