coldfusioncfccoldfusion-2016

How to conditionally pass arguments to an instance of a CFC?


I am currently using the <cfinvoke> tag to invoke CFCs and pass them arguments. This is really convenient because I can use tags to pass in only the parameters that I want like such:

<cfinvoke component="pathtofolder.imagehandler" method="SomeMethod" argumentcollection="#VARIABLES#" returnvariable="ImageHandlerResult">
<cfif structkeyexists(ARGUMENTS, 'Argument1')>
<cfinvokeargument name="Parameter1" value="#ARGUMENTS.Argument1#" />
</cfif>
<cfif structkeyexists(ARGUMENTS, 'Argument2')>
<cfinvokeargument name="Parameter2" value="#ARGUMENTS.Argument2#" />
</cfif>
<cfif structkeyexists(ARGUMENTS, 'Argument3')>
<cfinvokeargument name="Parameter3" value="#ARGUMENTS.Argument3#" />
</cfif>
</cfinvoke>
<cfreturn ImageHandlerResult /> <!--- how do you get this using createObject/new method? --->

If I use the new() or createObject() methods to create an instance of the CFC and then call the methods within this newly created instance I'm not able to conditionally pass arguments. I get errors at runtime.

<cfset ImageHandler = new pathtofolder.imagehandler()/>
<cfset ImageHandler.SomeMethod(
    <cfif StructKeyExists(ARGUMENTS, 'Argument1')>
    Parameter1 = ARGUMENTS.Argument1
    </cfif>
    <cfif StructKeyExists(ARGUMENTS, 'Argument2')>
    Parameter2 = ARGUMENTS.Argument2
    </cfif>
<cfif StructKeyExists(ARGUMENTS, 'Argument3')>
    Parameter3 = ARGUMENTS.Argument3
    </cfif>
)/>

How can I pass in arguments conditionally using the above method? Should I use the cfinvoke method on the new instance - in which case what is the point in making an instance and then using cfinvoke again when I could just stick to using cfinvoke on the actual CFC directly?


Solution

  • You can use argumentCollection. Argument collection is a structure and each key will be deconstructed as individual arguments.

    <cfset ImageHandler = new pathtofolder.imagehandler()>
    <cfset args = {}>
    <cfif StructKeyExists(ARGUMENTS, 'Argument1')>
      <cfset args.Parameter1 = ARGUMENTS.Argument1>
    </cfif>
    <cfif StructKeyExists(ARGUMENTS, 'Argument2')>
      <cfset args.Parameter2 = ARGUMENTS.Argument2>
    </cfif>
    <cfif StructKeyExists(ARGUMENTS, 'Argument3')>
      <cfset args.Parameter3 = ARGUMENTS.Argument3>
    </cfif>
    
    <cfset ImageHandler.SomeMethod(argumentCollection=args)>