Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ColdFusion - Converting a query into CFC setters

I am converting an older site to CF 10 and wanted to bring forward some of my helper code.

The code looks at a query, finds things that are in our instance, and populates them:

<cffunction name="populateSelf">
    <cfargument name="source" type="query" required="yes" />
    <cfif arguments.source.recordcount EQ 1>
        <cfloop list="#arguments.source.columnlist#" index="local.col">
            <cfif structKeyExists(variables.instance, local.col)>
                <cfset variables.instance[local.col] = arguments.source[local.col]) />
            </cfif>
        </cfloop>
    </cfif> <!--- one record? --->
</cffunction>

I have replaced the structKeyExists(variables.instance, local.col) with a handy evaluation of our current properties using 'getMetaData()', but I am having trouble with the next line: <cfset variables.instance[local.col] = arguments.source[local.col]) />

If I change it to <cfset this[local.col] =arguments.source[local.col] />, it ignores the implicit setters and just puts the results in the this scope...

In order to try and call our setters, I tried this bit of code:

<cfset setValue =arguments.source[local.col] />
<cfset evaluate("set#local.col#('#setValue#')" />

but this seems complicated and error prone (have to escape any "'"s in the strings too).

What is the best way to use a query to load some or all of a CFCs properties without having to explicitly call this.setPROPERTYNAME(query.COLUMN) possibly several dozen times????

like image 479
Stephen F Roberts Avatar asked Jan 01 '13 04:01

Stephen F Roberts


2 Answers

So if I am reading all this correctly, your question is actually "how do I call a method dynamically?", and all the rest of it is set dressing?

You can use a string to set the dynamic variable name, then set a function reference to that, then call the function via the reference:

myMethodName = "set#local.col#";
myMethodReference = this[myMethodName];
myMethodReference(arguments.source[local.col]);
like image 176
Adam Cameron Avatar answered Sep 16 '22 22:09

Adam Cameron


If you want to call methods dynamically you can use cfinvoke

<cfinvoke method="set#property#">

Make sense?

like image 35
baynezy Avatar answered Sep 17 '22 22:09

baynezy