所有情况都在组件方法中使用cfscript编写。假设我正在尝试动态调用MyComponent组件中的
setName(required string name)
方法。所有情况都定义以下变量:var myComp = new MyComponent();
var myMethod = "setName";
var args = {"name"="foo"};
use
evaluate()
for the jobevaluate("myComp.#myMethod#(argumentCollection=args)");
pros: is done with very little code
cons: code is not very 'clean' and use of evaluate() seems to have an 'evil' reputation in the online community. I wouldn't want my code to be evil.use a cfml wrapper for
<cfinvoke>
invoke("MyComponent", myMethod, args);
pros: I can use all functionality of
cfinvoke
cons: It creates a new instance ofMyComponent
with every invoke.create a
dynamicMethod
method in MyComponentmyComp.dynamicMethod(myMethod, args);
dynamicMethod of MyComponent:
public any function dynamicMethod(required string methodName, required struct argumentColl){ var cfcMethod = variables[arguments.methodName]; return cfcMethod(argumentCollection=arguments.argumentColl); }
pros: I can finally call myComp directly. Most comfortable solution so far.
cons: I can now call private methods of MyComponent via dynamicMethod.
(I've also tried the 'function as variable' solution outside of MyComponent, but then the function looses its working context. e.g. if MyComponent would extend a component, the 'super' scope would no longer refer to the extended component).
这些解决方案似乎都不完美,那么从不同的控制器调用动态函数没有其他方法吗?
如果没有,这些解决方案中哪一个是最好的?
欢迎任何建议,谢谢。