Function Libraries

One of the great things about UDFs is that you can have more than one in a single template. This gives you the ability to take all of the UDFs that you use in a particular application or web site and keep them in a single template, commonly referred to as a library. Depending on the number of UDFs used by your application, you may want to create one or more libraries, grouping your UDFs by functionality. The more UDFs you have, the more it may make sense to create multiple UDF libraries.

Here’s an example of a small UDF library with several UDFs for calculating the area of various geometrical shapes:

<cffunction name="AreaCircle" returntype="Numeric" output="No">
  <cfargument name="Radius" type="Numeric" required="Yes">
  <cfreturn Pi( ) * Arguments.Radius^2>
</cffunction>
   
<cffunction name="AreaRectangle" returntype="Numeric" output="No">
  <cfargument name="Length" type="Numeric" required="Yes">
  <cfargument name="Width" type="Numeric" required="Yes">
  <cfreturn Arguments.Length * Arguments.Width>
</cffunction>
   
<cffunction name="AreaTriangle" returntype="Numeric" output="No">
  <cfargument name="Base" type="Numeric" required="Yes">
  <cfargument name="Height" type="Numeric" required="Yes">
  <cfreturn 0.5 * Arguments.Base * Arguments.Height>
</cffunction>

To use any of these functions in any of your templates, just cfinclude the template at the beginning of the page that needs them. If you save the library we just created as _areaLib.cfm, you call it like this:

<cfinclude ...

Get Programming ColdFusion MX, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.