A few days ago I posted about how you could use ColdFusion to track the number of sessions in an application. One of themes of that post was how much easier Application.cfc makes this process. If you haven't read the first post, please do so now. I'll wait.
So first lets look at the Application.cfc file:
<cfcomponent output="false">
<cfset this.name = "sessioncounter2">
<cfset this.sessionManagement = true>
<cffunction name="onApplicationStart" returnType="boolean" output="false">
<cfset application.sessions = structNew()>
<cfreturn true>
</cffunction>
<cffunction name="onSessionStart" returnType="void" output="false">
<cfset application.sessions[session.urltoken] = 1>
</cffunction>
<cffunction name="onSessionEnd" returnType="void" output="false">
<cfargument name="sessionScope" type="struct" required="true">
<cfargument name="appScope" type="struct" required="false">
<cfset structDelete(arguments.appScope.sessions, arguments.sessionScope.urltoken)>
</cffunction>
</cfcomponent>
The first method I have is onApplicationStart. Note that, outside of the cffunction and return tags, it is one line. For the heck of it, here is the code from the Application.cfm version:
<cfset needInit = false>
<cflock scope="application" type="readOnly" timeout="30">
<cfif not structKeyExists(application,"sessions")>
<cfset needInit = true>
</cfif>
</cflock>
<!--- Yes, I do need to make it. --->
<cfif needInit>
<cflock scope="application" type="exclusive" timeout="30">
<cfif not structKeyExists(application,"sessions")>
<cfset application.sessions = structNew()>
</cfif>
</cflock>
</cfif>
Which do you prefer? So just to be clear - the onApplicationStart method creates the structure we will use to count the sessions. We could use a list, but a structure makes it easy to insert/delete items.
Moving on - the next method, onSessionStart, handles writing our session key to the Application structure. Again - notice that it is one line. This isn't much different from the Application.cfm file - but - there is one crucial difference. Because ours is in onSessionStart, it gets executed one time only.
The last method, onSessionEnd, handles removing the session key from the application structure. If you remember from the last post I had to handle that myself in the sessionCount UDF. Now I don't need to worry about it. I simply remove myself from the Application structure. Do remember though that onSessionEnd can only access the Application scope via the passed in argument.
Ok - so lastly, let's look at the sessionCount UDF:
<cffunction name="sessionCount" returnType="numeric" output="false">
<cfreturn structCount(application.sessions)>
</cffunction>
Nice, eh? You may ask - wny bother? I could certainly just output the result of the structCount myself. But the UDF is nice. What if I change from using an Application structure to a list? Or what if I store active sessions in the database? The UDF gives me a nice layer of abstraction.