Switch between Client and Session Variables

Many developers often ask whether client variables or session variables are better. The answer to this question (as with many others) is "It depends". A common suggestion is to create some kind of wrapper for these scopes to allow easy switching.

The SessionMgr component provides this functionality. It will allow you to specify Client or Session scope when you intialize it. After that, you can have SessionMgr handle all of your Client/Session data. If you ever need to change which scope you use, just change the scope passed in and re-initialize SessionMgr - no need to change any other code.

SessionMgr will ensure proper locking and handle complex variables in Client scope, so you don't have to worry about those issues in your code.

SessionMgr is part of the com.sebtools package, so it will need to be in com/sebtools in your custom tags directory, in a sebtools directory of a /com mapping, or under /com/sebtools from the root of your site.

To instantiate SessionMgr into Application.SessionMgr using Client variables, you can use the following code:
<cfset Application.SessionMgr = CreateObject("component","com.sebtools.SessionMgr").init("Client")>

To use Session variables instead, simple change that code to this:
<cfset Application.SessionMgr = CreateObject("component","com.sebtools.SessionMgr").init("Session")>

SessionMgr will throw an error if you try to use any other scope.

In order to set a variable in SessionMgr (for example to set the "foo" variable to a value of "bar"):
<cfset Application.SessionMgr.setValue("foo","bar")>

To get the value of the "foo" variable:
<cfset myvar = Application.SessionMgr.getValue("foo")>

To check if "foo" variable exists:
<cfif Application.SessionMgr.exists("foo")></cfif>

To set "foo" variable to "bar" only if it doesn't already have a value:
<cfset Application.SessionMgr.paramVar("foo","bar")>

To delete "foo" variable:
<cfset Application.SessionMgr.deleteVar("foo")>

To get a dump of Client/Session scope:
<cfset Application.SessionMgr.dump()>

Hopefully you may find this as useful as I have.

The code should be an example of good practices (not best practices). If you see any reason why it isn't, let me know so that I can make the appropriate adjustments.

Good luck!

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
I'm excited!
# Posted By Phillip Senn | 12/7/05 7:24 PM
Phil's excited, and that makes me a little nervous. What happens when you start to talk about execution scripting and XML? Shudder...
# Posted By Mike from Dubai | 5/25/06 5:10 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.