Quickmute
Quickmute

Reputation: 1723

ColdFusion calling session function

I have a user object that I would like to have in the session variable and be able to update as needed. How do I call a function in an existing user object that will manipulate the existing variable. I found way to call the function, but it's not calling the existing object, instead I suspect it's instantiating a new object before calling the function.

In Application.cfc:

<cffunction name = "onSessionStart" output="no">
    <cfobject name="session._user" component="user"/>
    <cfscript>
    ...
    session._user.init();
    </cfscript>
</cffunction>

In User.cfc:

<cffunction name = "init">
    <cfscript>
        variables.attributes.variable1 = 0;
    </cfscript>
</cffunction>

<cffunction name="changeVariable" access="public">
    <cfargument name = "somename">
    variables.attributes.variable1 = arguments.somename;
</cffunction>

Later on in login.cfm, call session._user.changeVariable(2)

If this isn't possible, I'll end up writing to and from database to keep track of user properties instead of using session variable.

Upvotes: 2

Views: 165

Answers (2)

Chris Tierney
Chris Tierney

Reputation: 1539

I've never quite done it that way so I'm not sure how that works, but normally I would create the user.cfc file and store the instance in the session.

<cffunction name="onSessionStart" output="false">
    <cfset session._user = new user()>
</cffunction>

I would also consider possibly using a framework and/or ORM to handle this stuff for you.

Upvotes: 0

Matt Busche
Matt Busche

Reputation: 14333

In onSessionStart create the object and set it into the session. If you are using CF10+ you can use new() in CF9 and lower you need to use createObject().

<cffunction name="onSessionStart">
  <!--- in CF10+ new calls init() automatically --->
  <cfset session._user = new user()> 
  <!--- CF9 or lower --->
  <cfset session._user = createObject('user').init()>
</cffunction>

In login.cfm simply say this to update the session variable

<cfset session._user.changeVariable(2)>

Upvotes: 4

Related Questions