Skip to main content
Known Participant
October 8, 2009
Question

Best place to put cffunctions?

  • October 8, 2009
  • 2 replies
  • 1198 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?

ilssac
Inspiring
October 8, 2009

Just realize if you are putting the function into the session scope, each and every user is getting an entire copy of the function in the server's memory.

Depending on the purpose of the function and how you are using it, this may or may not be a lot of memory used up unnecessarily.

If the function is something that each user does not need their very own copy then it might make more sense to put it into the application scope.  Then there would be one copy of the function that all users utilize.  You could, of course, do that in the OnApplicaitonStart() function of the Application.cfc.