CFC Best Practices Tips and Tricks Raymond Camden
CFC Best Practices, Tips, and Tricks Raymond Camden jedimaster@mindseye. com
Agenda • • Basic (but real!) Examples Best Practices (Suggestions) Tips and Tricks Resources
Examples • www. cflib. org üCFCs serve as DB abstraction • Resource. Bundle CFC üLocalization Utility • Simple. CMS üSimple CMS based on CFCs
Best Practices • Control white space generated by CFC <cfcomponent display. Name="Example" output="false"> <cffunction name="test" return. Type="string" access="public" output="false"> <cfreturn "This is a boring function. "> </cffunction> </cfcomponent>
Best Practices • Supply Optional Attributes <cfcomponent display. Name="Example 2" output="false"> <cffunction name="test" return. Type="string" access="public" output="false" hint="This function does blah using Foo's logic. "> <cfargument name="argone" type="string" required="true"> <cfargument name="argtwo" type="numeric" required="false" default="0"> <cfreturn arguments. argone & " with the number " & arguments. argtwo> </cffunction> </cfcomponent>
Best Practices • Use the VAR scope! <cfcomponent display. Name="Example 3" output="false"> <cffunction name="test" return. Type="string" access="public" output="false"> <cfargument name="argone" type="string" required="true"> <cfset var i = 0> <cfloop index="i" from=1 to=10>. . . </cfloop> </cffunction> </cfcomponent>
Understand Data Scopes • • Variables This Arguments Function Local
Cache CFC Instances • CFC creation can be slow. • Use create. Object/cfobject to create an instance. • <cfinvoke> (typically) works with new instances.
Pseudo-Constructor • Any code not inside <cffunction>. • Useful to initialize variables. • Blue. Dragon has <cfconstructor>
Dealing with Application Variables • Application. cfm and when it's run: üFlash Remoting/WS calls üSame folder • Don't rely on it! • Application CFC
Inheritance/Super • Use for Is-A, not Has-A üIn other words, inheritance is used when a CFC defines as "is a" relationship with it's parent. It should not be used for simple code re-use. • Super allows for a child method to extend a parent method.
Pass by Ref/by Value • Values passed to CFC methods follow the same rules as values passed to UDFs. • The following are passed by reference: üStructures üQueries üOther "comlpex" objects (including CFCs)
Resources • www. cfczone. org • cfcdev mailing list • Top Ten Tips article by Rob Brooks-Bilson ühttp: //www. oreillynet. com/pub/a/javascript/2003/09 /24/coldfusion_tips. html? page=1 • CFC Best Practices by Nathan Dintenfass ühttp: //www. dintenfass. com/cfcbestpractices/
- Slides: 13