Jarede
Jarede

Reputation: 3488

coldfusion 9 dynamically call method

I'm attempting to build a method call from strings that have been passed into an object that refer to another object.

normally when calling an object we write the code like this:

application.stObj.oNewsBusiness.getNews(argumentCollection=local.stArgs);

However what I have done is created an array that contains the object name, the method name and the argument collection.

<cfscript>
local.stArgs = {};
local.stArgs.nNewsID = 19;
local.stArgs.sAuthor = "John";

local.aData = [];
local.aData[1] = local.stArgs;
local.aData[2] = "stObj.oNewsBusiness";
local.aData[3] = "getNews";
</cfscript>

however i am struggling to recombine all this to be a method call.

UPDATE using suggestion but still with issue

While cfinvoke seems to work for:

<cfinvoke component="#application.stObj.oNewsBusiness#" method="#local.sMethod#" argumentcollection="#local.stArgs#" returnvariable="local.qData"></cfinvoke>

it doesn't work when doing something like:

<cfscript>
local.stArgs = local.aData[1];
local.sObject = local.aData[2];
local.sMethod = local.aData[3];
</cfscript>
<cfinvoke component="application.#local.sObject#" method="#local.sMethod#" argumentCollection="#local.stArgs#" returnvariable="local.qData"></cfinvoke>

it generates an error:

Could not find the ColdFusion component or interface application.stObj.oNewsBusiness

Upvotes: 2

Views: 996

Answers (3)

Jason M
Jason M

Reputation: 510

<cfinvoke component="application.#local.sObject#" method="#local.sMethod#"argumentCollection="#local.stArgs#" returnvariable="local.qData"></cfinvoke>

from your update won't work because there are no # signs around the component variable.

You could do

<cfset local.componentName = "application." & local.sObject>
<cfinvoke component="#local.componentName#" method="#local.sMethod#"argumentCollection="#local.stArgs#" returnvariable="local.qData"></cfinvoke>

There's probably an inline way of combining application. with the variable on the cfinvoke call, but I don't know off the top of my head.

Edit: Dan Wilson's comment does it better in an inline way.

Upvotes: 0

Tim Cunningham
Tim Cunningham

Reputation: 329

Dan is correct CFInvoke is the way to go

<cfinvoke component="#mycomponentname#" method="get"  arg1="#arg1#" arg2="#arg2#" arg3=..>

Upvotes: 2

Dan Wilson
Dan Wilson

Reputation: 126

CFInvoke is generally used to handle dynamic method calls.

http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7e0a.html

CFInvoke has an argumentcollection attribute so you can pass your arguments in the way you are used to.

Upvotes: 7

Related Questions