By default, ColdFusion passes simple types (like numeric, string, and GUID) by value to functions. I'd like to pass a simple type by reference.
I'm currently wrapping a simple value in a struct (they get passed by reference). This solves my problem but it is very ugly:
<!--- TheFunctionName---->
<cffunction name="TheFunctionName">
<cfargument name="OutVariable" type="struct">
<cfset OutVariable.ID = 5>
</cffunction>
<cfset OutVariable=StructNew()>
<cfset TheFunctionName(OutVariable)>
<!--- I want this to output 5--->
<cfoutput>#OutVariable.ID#</cfoutput>
I'd rather something like this:
<!--- TheFunctionName---->
<cffunction name="TheFunctionName">
<cfargument name="OutVariable" passbyref="true">
<cfset OutVariable = 5>
</cffunction>
<cfset TheFunctionName(OutVariable)>
<!--- I want this to output 5--->
<cfoutput>#OutVariable#</cfoutput>
AFAIK, there's no way to pass simple values by reference in ColdFusion. The only workaround I can think of is the one you're already using.
Instead, I would suggest trying to restructure your program to work with the grain of the language. In cases where there's only one simple value to "modify", you could just make your function return the new value, and call it like:
<cfset SomeVar = TheFunctionName(SomeVar)>
In cases where you're modifying multiple values, take a step back and think about whether it's possible to bundle those multiple values up into a CFC with your mutator functions becoming methods of the CFC. This could be clearer and more maintainable solution anyway.
You can arrange for the variables used outside and inside the function to be in a scope that exists in both code areas. For example, if you put a variable in the "session" or the "request" scope you will be able to access it from within the function. The changes made will persist.
Note that when you are doing this you aren't actually "passing" the variables to the function. The function just assumes the variable exists or creates it, depending on how you code it.
<cffunction name="TheFunctionName">
<cfset Request.StrVar = "inside function<br />" />
</cffunction>
<cfscript>
Request.StrVar = "outside function<br />";
WriteOutput(Request.StrVar);
TheFunctionName();
WriteOutput(Request.StrVar);
</cfscript>
About ColdFusion Scopes
If there is any doubt about the calling page declaring the variable in advance when it is required you'll have to do some legwork with the <cfparam> tag or IsDefined() function.
If you:
declare the function inside of a CFC
invoke the function using <cfinvoke>
You would be able to specify the <cfinvoke> parameter "returnvariable", and then output that variable however you like.
<cfinvoke component="this" method="TheFunctionName" returnvariable="blah">
<cfinvokeargument name="data" value="whatever" type="string">
<cfreturn data>
</cfinvoke>
<cfdump var="#blah#">
If you are writing everything in cfscript, then I would go with what SurroundedByFish said.
Related
I wrote the following function:
<cffunction name="check_session_valid" returntype="boolean">
<cfif NOT StructKeyExists(session,"username") OR (len(session.username) EQ 0)>
<script>location.href = 'logout.cfm'</script>
<cfabort>
</cfif>
<cfset session.myApp_start = now()>
<cfreturn true>
</cffunction>
In my .cfm page, I can call that function using
<cfset session_valid = application.lib.check_session_valid()>
OR
#application.lib.check_session_valid()#
What's the difference? Best practice?
Since you asked about best practice, which is a matter of opinion, I think you can improve your function by having it returning either true or false depending on whether or not session.username exists and has a length greater than 0. Then you can use it like this:
<cfif application.lib.check_session_valid()>
code for this condition
<cfelse>
<cflocation href = "logout.cfm">
<!--- note that cfabort is not necessary --->
<cfif>
Regarding your specific question, I think the extra variable, session_valid, is a waste of typing. However, that is simply my opinion.
Not related to your question, I found it curious that you would direct users to a page called logout.cfm. Often users are directed to a page that allows them to log in.
To be honest, both are valid and both would be considered best practice depending on what you are trying to do.
My rule of thumb is if I will need to use the result of a function call more than once, I will set it to a variable
myResult = application.lib.check_session_valid();
If I will only need to use the variable once I would do what Dan mentioned
if( application.lib.check_session_valid() ){
// Do stuff
}
The difference between the examples you showed are
<cfset session_valid = application.lib.check_session_valid()>
This will set the variable named session_valid to whatever is returned from the call to check_session_valid().
#application.lib.check_session_valid()#
This will, in .cfm pages, simply render the value returned from the call to check_session_valid() assuming it is inside of a <cfoutput> tag. There are other places this would also render the value, such as inside a <cfsavecontent>.
I am building a website where I have followed MVC to manage my code without using any frameworks. I have put all of my queries inside cfcs and am initializing them inside my Application.cfm, storing them in application variables like below:
<cfset aplication.customerProfileObject=
createObject("component","cfc.customerprofile").init()>
To perform any query operations, I have made a function and then call it anywhere like this:
<cfset selectedCustomerOb =
application.customerProfileObject.getContactCustomerProfileDetail(session.userid)>
I don't know what is causing the issue, but sometimes a user accesses another user's data. How is that possible? Is it assessing another user's session data or have I initialized the cfc wrong?
Application settings are below:
<cfapplication name="MyDataSourceName"
sessionmanagement="Yes"
setclientcookies="yes"
setdomaincookies="yes"
loginstorage="session"
sessiontimeout="#CreateTimeSpan(0, 2,0,0)#">
CustomerProfile.cfc
<cfcomponent>
<cffunction name="init">
<cfreturn this>
</cffunction>
<cffunction name="getContactCustomerProfileDetail" returntype="query"
description="Returns customer contact details by contactid"
access="public">
<cfargument name="ccId" type="numeric" required="yes">
<cfquery name="getContactCustomerProfileDetail"
datasource="#Application.ds#"
dbtype="ODBC"
username="#Application.UserName#"
password="#Application.Password#">
<!-------My query here--->
</cfquery>
<cfreturn getContactCustomerProfileDetail>
</cffunction>
</cfcomponent>
As Adam says you need to do this:-
<cffunction name="getContactCustomerProfileDetail" returntype="query"
description="Returns customer contact details by contactid"
access="public">
<cfargument name="ccId" type="numeric" required="yes">
<cfset var getContactCustomerProfileDetail = false>
<cfquery name="getContactCustomerProfileDetail"
datasource="#Application.ds#"
dbtype="ODBC"
username="#Application.UserName#"
password="#Application.Password#">
<!-------My query here--->
</cfquery>
<cfreturn getContactCustomerProfileDetail>
</cffunction>
The reason you are getting the problem is because your CFC instance is in a shared scope (application) and you have not var'd the query variable. This means that it is getting set into the variables scope of the CFC instance. Which means that multiple threads can overwrite this value. By just varring the variable as I have shown you make the variable local to the function and so each call to that function creates a localised and thus thread-safe variable.
Basically you should var all local variables in functions as a matter of habit. This code would never pass code review anywhere I have worked.
You're not actually including the relevant bit of the code to answer this... which would be the code within getCustomerProfileDetail().
However I would assume you don't have all your variables VARed in it, which means they go in the CFC's variables scope, which is shared with every user in the application.
But, as I say, you're not giving us the correct info to really answer this accurately. I suggest updating your question to include the relevant code.
I am using the technique detailed in this answer to manage a library of small utility functions. (Essentially, each function is loaded as a "mix-in" using cfinclude.)
I have need, however, to know the names of the functions that the object has (once instantiated). A cfdump on the object only shows the init function which is written directly in the CFC.
Some more detail:
I am creating the object in the application scope in OnApplicationStart().
<cfset application.udfs=createObject("component","extensions.udfs").init()>
However, to save the developers from having to constantly write application.udfs.foo(), I thought I'd grab all of the functions and drop them in to the variables scope in OnRequestStart(), so that these hypothetical developers could just write foo().
<cfset foo=application.udfs.foo>
Obviously, though, this needs to be dynamic and to happen for each of the functions in the object, no matter how many there are. If I repeat this line for every function I've lost whatever I'd gained by having a library that is dynamically generated.
I thought perhaps I could use a collection loop, but that was invalid. I am fairly certain there's a way to get the list of methods in an object, but I have not yet been able to find it.
Any clues?
By the by, my fallback is going to be to copy the application.udfs object to a local object with a nice short name (like "u") so that the developers can simply type u.foo(), so no need to suggest that if what I want to do can't be done.
This should allow you to import all your udfs into the global variables scope:
StructAppend(variables, application.udfs);
I think GetMetaData should help you.
Here another interesting option suggested by Ben Nadel:
Check out the detail in his blog entry: http://www.bennadel.com/blog/1776-Creating-Globally-Accessible-User-Defined-Functions-In-ColdFusion-Safer-Version-.htm
UDF.cfc
<cfcomponent
output="false"
hint="I define user defined functions.">
<cffunction
name="getMessage"
access="public"
returntype="string"
output="false"
hint="I return a test message.">
<cfreturn "I am defined in the UDF component" />
</cffunction>
</cfcomponent>
Application.cfc
<!--- Define the application. --->
<cfset this.name = hash( getCurrentTemplatePath() ) />
<cfset this.applicationTimeout = createTimeSpan( 0, 0, 5, 0 ) />
<!---
Add all of our "global" methods to the URL scope. Since
ColdFusion will automatically seach the URL scope for
non-scoped variables, it will find our non-scoped method
names.
--->
<cfset structAppend(
url,
createObject( "component", "UDF" )
) />
Have a look at the following function in a CFC (I'm using ColdFusion 9).
Assuming that oldObject is true and that it is type 1, does ColdFusion continue on until the end of the function and create the new object, or does it "bust out" on <cfset respond(result=false)> and aborts any further processing in the function?
<cffunction name="myFunction" access="private">
<cfargument name="key">
<cfset oldObj = model("myModel").findOne(arguments.key)>
<cfset local.data = 1>
<cfif isObject(oldObj)>
<cfif oldObj IS 1>
<cfset respond(result=false)>
<cfelse>
<cfset local.data = 2>
</cfif>
</cfif>
<cfset newObj.new(local.data)>
<cffunction>
The idea is this:
If oldObject (1) exists and (2) is of type 1, bust out and don't do anything.
If oldObject exists and is NOT of type 1, then modify local.data and create new object.
If oldObject does not exist, just create the new object with unmodified local.data.
The respond() function simply returns data to the user via a JSON struct. I've omitted a lot of code since this is a theoretical question.
Your algorithm continues on to the end of the function. Only a <cfreturn> would exit the function before the end. So <cfset newObj.new(local.data)> will always be reached.
To output JSON inline (i.e. <cfoutput>#json#</cfoutput>.), ensure respond() does not specify <cffunction name="respond" output="false" ...>.
Note, assuming the larger object these functions reside in is stateful, a cleaner approach would be having the client call methods as appropriate. Have the object internally cobble together the response as part of its state. And then finally, the client calling something along the lines of a getResponse() function.
I simply want to define a function in application.cfc and expose it application wide to all requests. Preferably the "assignment" would only happen on application startup.
Is the preferred method to do something along the lines of this:
<CFCOMPONENT OUTPUT="FALSE">
<CFSET this.name = "Website">
<CFSET this.clientManagement = true>
<CFSET this.SessionManagement = true>
<CFFUNCTION NAME="GetProperty" OUTPUT="False">
<CFARGUMENT NAME="Property">
<CFRETURN this.Props[Property]>
</CFFUNCTION>
<CFFUNCTION NAME="OnApplicationStart" OUTPUT="FALSE">
<CFSET Application.GetProperty = GetProperty>
.
.
.
or is there something better?
By default, GetProperty will be visible in Variables scope already, this can be sufficient for many usages (in .cfm templates).
If you want to use these methods directly in the components, referencing them in the Application scope is fine.
Though I do this with Request scope in the onRequestStart(), it's just my personal preference. Something like this:
request.udf = {};
request.udf.halt = halt;
Please note that best practice in general is incapsulating the objects and having them referenced in variables scope of the host object. I typically do this when initializing the object, simply pass previously created objects as init() arguments.
P.S. Nowadays it is recommended to use lower case for tags and their attributes. Kind of good coding practices.
The best way to store site specific config data is probably going to be to create a new component named something such as SiteConfig.cfc with methods such as getProperty(propertyName) and setProperty(propertyName, value). You would then store this CFC in the application scope by doing the following inside Application.cfc's onApplicationStart method like:
<cfset application.siteConfig = createObject("component", "SiteConfig").init() />
Back to your original question though about storing a UDF in the Application scope, below is a way to do that. The basis is that in onApplicationStart you will create a new application persisted struct with your site's config properties like siteName and whatever else. Then a function is stored in a CFM file which is cfincluded only in onApplicationStart, then copied into the application scope. This means that all your regular page CFM files can use application.getProperty(propertyName).
Since the function is only created once and stored in the application scope it satisfies your original question's requirements about "assignment would only happen on application startup".
Hope this helps a bit!
getProperty.function.cfm
<cffunction name="getProperty" output="false">
<cfargument name="propertyName" type="string" required="true" />
<cfreturn application.config[propertyName] />
</cffunction>
Application.cfc
<cffunction name="onApplicationStart" output="false">
<cfset application.config = structNew() />
<cfset application.config.siteName = "My App's Display Name" />
<cfinclude template="getProperty.function.cfm" />
<cfset application.getProperty = variables.getProperty />
</cffunction>
test.cfm
<cfset propertyValue = application.getProperty("siteName") />
<cfdump var="#propertyValue#" />
You might consider creating a seperate "properties" CFC and instanciating it as
a singleton in the SERVER scope then it will be available from any CFML page even
if it isn't part of an application. If you go this route then there is no "server
start" event to bind to. Instead you can put this in the contructor of application.cfc
or in the body of application.cfm
<cfif not structkeyexists(server,"properties")>
<cflock name ="loadProperties"
timeout ="10"
type ="exclusive"
>
<cfif not structkeyexists(server,"properties")>
<cfset server.properties =
createObject("component","path-to-props.cfc")
.init({..inital properties..})
>
</cfif>
</cflock>
</cfif>
The lock code is to prevent the overhead of creating and assigning the UDF on every
request. This also allows the properties instance to persist so that having a
properties.SetProperty() function will work
you might also want to use the technique discussed here