Interesting CFINVOKE Trick

As you know, CFINVOKE allows you to call a method on a CFC, or a CFC instance, or against a web service. However, I was looking at some code today from fellow developer Michael Hodgdon, and notice the following code. (Well, this isn’t the code he used, but demonstrates the point of this entry.)

<cffunction name="foo">
   <cfreturn now()>
</cffunction>

<cfinvoke method="foo" returnVariable="time">
<cfoutput>#time#</cfoutput>

Michael used CFINVOKE to call a UDF defined in the current page. I wasn’t aware that CFINVOKE could do that. Now, you may be thinking, “So what!”, but there is a use for this. CF allows you to dynamically pass arguments to UDFs and CFCs by using the argumentCollection attribute. (You can do the same with custom tags using attributeCollection.) This is handy feature. However, it doesn’t make for easy to read code. When you use CFINVOKE, however, you can have a cleaner call. Here is a pseudo-code example:

<cfinvoke component="#c#" method="foo">
<cfinvokeargument name="name" value="Jacob">
<cfif tillTuesday>
<cfinvokeargument name="vegimite" value="sandwhich">
</cfif>
</cfinvoke>

For complex UDFs (or CFC methods), this syntax may be a bit easier to read.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments