CFComponent
For easy maintenance, Coldfusion has come up with a feature which is . This features has the capability to enclose functions for easy sharing from multiple files. As such, codes within the the body of these tags can be executed only when the component is instantiated.
So let’s look at how we can make use of the component.
First we will create a file, eg test.cfc which will stores the relevant functions such as interacting with the database. Content will be as follows:
<cfcomponent>
<cffunction name=”GetProductByID” access=”public” returntype=”query”>
<cfargument name=”ProductID” type=”string” required=”yes”>
<cfquery datasource=”#application.dsn#” name=”data”>
SELECT *
FROM catalogue
WHERE productid = ‘#CompanyID#’
</cfquery>
</cffunction>
<cfreturn data>
</cfcomponent>
With references from the codes as shown above, you could see that the function requires a string to be included into the SQL statement and thereafter returns a query as the output. To display the records, you will need the following codes:
<cfset comtest = createObject(”component”,”exec.test”)>
<cfset prod = comtest.GetProductByID(”#form.ProductID#”)>
<cfoutput query=”prod”>
#productname#
</cfoutput>
As you can see from the codes above, the component is instantiated on the first line. Next the variable “products” is being declared to contain the query results from the function “GetProductByID”. The results are then displayed via the
Simple as it can be. Do try it out and you will realise how convenient it can get as the functions stored within can be shared across multiple files.
