coldfusioncomponentsdesign-decisionscreateobjectcfinvoke

What is the difference between using cfinvoke and createObject to run a component function?


In my company's code, I've often seen component files used by initializing an object of that component and calling the methods off the object. However, it seems to me somewhat more straightforward to use the cfinvoke method, especially when only using one method from the component file. What are the differences between these 2 methods of calling a component function and what are the pros/cons of each? When should I use which?


Solution

  • cfinvoke can only be used in tags.

    createObject can be used in both tags & cfscript and tends to be a bit slimmer / easier to read IMO.

    Until recently I avoided using cfinvoke because I found it "bulky" but a pro of it is you can dynamically loop over the methods within a CFC. In createobject you can't.

    So if for example I've got a CFC which has the methods - method1, method2, method3, method4. I can loop over them like so:-

    <cfloop from="1" to="4" index="element">
       <cfif structKeyExists(this,'getMethod#element#')>
    <cfinvoke component="#this#" method="getLine#local.element#" returnVariable="methodValue"></cfinvoke>
    <cfset arrayAppend(myArray,methodValue) />
       </cfif>
    

    --

    Another thing to note is that some sharing hosts lock down on createobject. Mainly because of the access it gives to the underlining Java.