如何使用cfscript从不同组件动态调用方法?

8
我正在寻找一种最佳方法,在cfscript中从不同的组件动态调用方法。注意,它涉及到一个不同的组件中的方法。到目前为止,我尝试了3种不同的方法,但似乎没有一种完全符合我的要求:
所有情况都在组件方法中使用cfscript编写。假设我正在尝试动态调用MyComponent组件中的setName(required string name)方法。所有情况都定义以下变量:
var myComp = new MyComponent();
var myMethod = "setName";  
var args = {"name"="foo"};
  • use evaluate() for the job

    evaluate("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 of MyComponent with every invoke.

  • create a dynamicMethod method in MyComponent

    myComp.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).

这些解决方案似乎都不完美,那么从不同的控制器调用动态函数没有其他方法吗?
如果没有,这些解决方案中哪一个是最好的?

欢迎任何建议,谢谢。


2
不要因为别人声称某些东西是“邪恶的”而回避它。确实有理由避免使用 evaluate 函数,你应该了解这些理由,而不是盲目相信不合格的负面评价。 - Peter Boughton
为什么你不能直接传递组件实例而不是它的名称给“invoke()”,这样每次都可以重用相同的实例? - lud
1个回答

7

分析得很好。

在您的包装函数中,您可以更加紧密地模拟 <cfinvoke><cfinvoke> 将采用组件路径或该组件实例(即对象)作为 COMPONENT 属性。因此,你对 "它每次调用都会创建一个新的 MyComponent 实例" 的反驳其实是无效的。

顺便说一下,ColdFusion 10 添加了一个invoke() 函数来实现这一点。 我注意到您正在使用 CF9,所以这对您没有帮助。 但它可能与其他可能看到这个问题的人有关。


1
谢谢。我不知道<cfinvoke>的组件参数可以是一个实例。同时,cf10函数看起来很有前途。不再需要包装器 :) - jan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接