We are going to look into using the ColdFusion components known as CFC’s and how easy they can make your web applications.
Some benefits of using CFCs
- Better security
- Reuseable code
- Faster applications
Our first step is to create a database & datasource, you can find all SQL & source files with the ZIP file attached to this thread (You may need to login to access).
<cfcomponent displayname="Users" hint="The main display name for the component"> <cffunction name="getUsers" hint="Gets users function" access="public" returntype="query"> <cfquery name="allUsers" datasource="yours_datasource"> SELECT * FROM users </cfquery> <cfreturn allUsers> </cffunction> </cfcomponent>
Our first bit of code is the main component as you can see we have ‘cfcomponent’ to start with the define the component. The next tag is the function which in this case is a query as we want to select everything from a database.
Next is the query, its just a normal query as you would do in ColdFusion. We then add a return so we can return the information from the database. Then we just close the tags.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Using CFCs</title> </head> <body> <cfinvoke component="users" method="getUsers" returnvariable="listUsers"></cfinvoke> <p>Get Users:</p> <ul> <cfoutput query="listUsers"> <li>#id#</li> </cfoutput> </ul> </body> </html>
The main area of this code you are probable looking at is the ‘cfinvoke’ tag, this calls the component. You may be asking why cant I just use a .cfm file for the query and do an include, well you could but an cfinclude will not be compiled by coldfusion and will run a lot slower where a CFC will be faster.
After the cfinvoke we can just do a cfoutput with the query as shown above.
Well thats it for CFC’s, working with them is better practice and also better when working in a team so you can start to extend each others components.
We have been hosting websites since 2002 and are always moving forward. All articles written under the Host Media author are created by the team who support our customers.