3

Say I want to call a static function from a CFC from within a cfscript block. As far as I know, the only method is using createObject() which returns a reference to the CFC object.

Is this good practice? I think I remember reading that cfinvoke definitely instanciated objects smartly and would not instanciate a static CFC multiple times. Is this even true, and if so, is this still true when using createObject()?

leokhorn
  • 505
  • 1
  • 4
  • 11

1 Answers1

10

CFOBJECT

CFOBJECT instantiates a component and creates a variable for it.

<cfobject type="component" name="path.to.my.CFC" name="myCFC" />

CFINVOKE

CFINVOKE can then reference the variable created by CFOBJECT, so that it doesn't have to re-create the object again.

<cfinvoke component="#myCFC#" method="foo" returnVariable="myValue" />

So you can call as many CFINVOKEs as you want on #myCFC# without recreating the object.

However, CFINVOKE can also implicitly create the object for you if you don't also use CFOBJECT.

<cfinvoke component="path.to.my.CFC" method="foo" returnVariable="myValue" />

Calling multiple functions in this manner will recreate the object each time.

CREATEOBJECT

createObject() works pretty much the same way. Either create the object first with a reference variable

<cfscript>
myCFC = createObject("component", "path.to.my.CFC");
myValue = myCFC.foo();
otherValue = myCFC.bar();
</cfscript>

or create the object with each function call.

<cfscript>
myValue = createObject("component", "path.to.my.CFC").foo();
otherValue = createObject("component", "path.to.my.CFC").bar();
</cfscript>

I prefer createObject() since I've been using CFSCRIPT as much as possible. And I always create the object first if I'm going to call multiple functions from it.

Leigh
  • 28,765
  • 10
  • 55
  • 103
Adrian J. Moreno
  • 14,350
  • 1
  • 37
  • 44
  • 1
    You can also use invoke(cfc, methodname [, arguments]) which takes a cfc instance or component name. – Chandan Kumar Feb 27 '14 at 20:10
  • So I take it that if I want to use a component as a class for static functions, I'd have to be careful to use createObject only once and keep the resulting instance in memory, such as in the Application scope? – leokhorn Mar 01 '14 at 08:26
  • 1
    @leokhorn That's the best practice. If you need the contents of a CFC to be available for the entire application, use the APPLICATION scope. If you have multiple instances, you might look at the SERVER scope so that all instances can use the same code & reduce memory. If you need an object to exist for the life of a user's login session, put it in the SESSION scope. Just be aware of memory usage and don't go overboard. – Adrian J. Moreno Mar 03 '14 at 16:32