Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CFWheels - Should I be locally scoping my Wheels actions?

Say I have a very simple controller like so:

<cfcomponent extends="Controller">
    <cffunction name="hello">
        <cfset time = Now()>
    </cffunction>
</cfcomponent>

In straight ColdFusion / Railo, I would be locally scoping all variables within this...but every wheels example I see does not.

This is probably going to earn me the dumbest question of the year award, but it was something I was thinking about, since nobody ever seems to demonstrate their Wheels code scoped correctly?

I would write it as follows:

<cfcomponent extends="Controller">
    <cffunction name="hello">
        <cfset local.time = Now()>
    </cffunction>
</cfcomponent>

I am just not sure if Wheels perhaps does something to remedy this regardless, and that's why I see what I do everywhere...or is it just a case of bad programming?

Thanks! Mikey

like image 250
Michael Giovanni Pumo Avatar asked Dec 16 '22 14:12

Michael Giovanni Pumo


1 Answers

Yes, you should be scoping it.

In your first example, you are (by not scoping) in most cases setting variables.time, which is local to the component instance, not to the function - if this is intended as a function-local variable (i.e. local.time) but is in the component's variable scope, and that component is shared/persisted, this may cause issues (though perhaps ones that only reveal themselves under heavy load).

If putting the variable in the variables scope is deliberate, it should still be explicitly scoped (as variables.time) otherwise it may cause issues if used on a Railo server with the localmode setting enabled.

Due to a cfWheels design decision (see links in comments), putting variables in the variables scope is required to pass variables to the view, even though they may technically be local to the function/view. (The controller instance lives for a single request, avoiding the issues this normally entails.) As mentioned in the previous paragraph, the localmode setting (described below) means it is still recommended to explicitly scope when you are not in control of all servers the code will be deployed to.

Railo's localmode setting

Railo (since v1) has had an admin setting called "localmode" which defines whether assigning an unscoped variable will go to the local scope, rather than the component's variables scope - making explicit var/local scoping not required (if you know your code will only be run on Railo servers with that setting enabled).

Since that setting is off by default, and ColdFusion does not have such a setting, cross-engine-compatible code should always scope such variable assignments to avoid this being an issue.

like image 58
Peter Boughton Avatar answered Feb 18 '23 22:02

Peter Boughton