Skip to main content
September 14, 2010
Answered

Best Practice for calling CFC

  • September 14, 2010
  • 2 replies
  • 929 views

Hi,

In a web application, if I need to call a CFC method from a different CFC, what would be considered as the best way of doing it?

For example, let's say I have two components: Customer and Product.  From a method functionA in Customer, I would like to call functionB in Product.  I can do one of the following, but which way is best practice and why?

1.  Create a Product object in functionA, and use it to call functionB

<cfcomponent name="Customer">

     <cffunction name="functionA">

          <cfset productObj = createObject('component', 'Product')>

          <cfset productObj.functionB()>

     </cffunction>

</cfcomponent>

2.  Pass a Product object when we initialize a Customer object, and use that to call functionB

<cfcomponent name="Customer">

     <cffunction name="init">

          <cfargument name="productObj">

          <cfset variables.productObj = arguments.productObj>

     </cffunction>

     <cffunction name="functionA">

          <cfset variables.productObj.functionB()>

     </cffunction>

</cfcomponent>

3.  Assume that Customer object has access to the Product object in the application scope

<cfcomponent name="Customer">

     <cffunction name="functionA">

          <cfset application.productObj.functionB()>

     </cffunction>

</cfcomponent>

Thank you very much.

    This topic has been closed for replies.
    Correct answer Dan_Bracuk

    I would use Method 1 because it gives you the most flexiblility.  While your known current requirements might dictate that it will be necessary to call the product cfc 100% of the time you call the customer cfc, something might come up in the future when it's not.  Method 2 would then be inefficient because it's running unnecessary code.

    2 replies

    Dan_BracukCorrect answer
    Inspiring
    September 14, 2010

    I would use Method 1 because it gives you the most flexiblility.  While your known current requirements might dictate that it will be necessary to call the product cfc 100% of the time you call the customer cfc, something might come up in the future when it's not.  Method 2 would then be inefficient because it's running unnecessary code.

    September 14, 2010

    Thank you both for answering my question.

    Inspiring
    September 14, 2010

    The first two are fine.  If the CFC being called is always gonna be the exact same one, then there's no prob directly referencing it in the calling CFC.  If the CFC could vary, then pass it in.

    If you're only using the CFC transiently, then you could use <cfinvoke> as well in this case.

    Directly accessing an application-scoped CFC within a method is poor practice.

    --

    Adam