Skip to main content
Known Participant
October 8, 2009
Question

Best place to put cffunctions?

  • October 8, 2009
  • 2 replies
  • 1197 views

Hi All,

I've created a cffunction which I need to access more or less from every page. Where is the best place to put it?

Can I put it in the Application.cfc? If yes how, and how can I call it from a page?

Thanks!

This topic has been closed for replies.

2 replies

Inspiring
October 8, 2009

I've created a cffunction which I need to access more or less from every page. Where is the best place to put it?

Can I put it in the Application.cfc? If yes how, and how can I call it from a page?

If it's just one function, then just put it in your Application.cfc.  Provided you have an onRequest handler specified, then all Application.cfc's functions are exposed to the calling template via the variables scope.  So if you have myFunction() defined in Application.cfc, you simply call it as

<cfset a = myFunction()>

If you have a bunch of functions which can be organised into a library, then you could stick 'em in a CFC, instantiate that in onApplicationStart, putting it in the application scope, and perhaps consider creating a variables-scoped reference to it in onRequest, for ease of calling.

--

Adam

Inspiring
October 8, 2009

My suggestion is to write the function in a separate cfc.  Then, in your onSessionStart function, create an object with that cfc.  That allows you to call the function with session.objectname.functionname()

Should you write any more udf's later, put them in the same cfc and everything will work.

Known Participant
October 8, 2009

Hi Dan,

Thanks very much, I love that idea! This will be very usefull.

The function(s) won't change often, would it be an idea to create the object in onApplicationStart?

Inspiring
October 8, 2009

Regarding:

The function(s) won't change often, would it be an idea to create the object in onApplicationStart?

If you take that approach, you have to restart the application whenever you edit the cfc.