Mar 3, 2008

CFC Simplicity

Ok so here is my quick and dirty primer on CFCs. CFCs are the defacto method for keeping your development nice and clean. For this example i am using a simple query and then invoking it in a web page. There are two files you need the CFC and the CFM calling the CFC.

So here are the files assuming you have a database registered in your Coldfusion administrator.

index.cfm
qryPerson.cfc

For the index page here are the contents with explanations and the cfc with explanations.

<!---First we are invoking the cfc component, it's method

which is the same name as the component, and giveing

the return variable the same name. You can get

creative but you will atleast have to have these

three items. --->

<cfinvoke component="qryPerson" method="qryPerson" returnvariable="qryPerson">

<!---Here ais the only argument I am passing the first name is frank.--->

<cfinvokeargument name="first" value="Frank">

<!---Closing the invoke.--->

</cfinvoke>

<!---Now I am dumping out the return query.--->

<cfdump var="#qryPerson#">

<!---If you want to actually present the return...do this...--->
<cfoutput query="qryPerson">

#first_name# #last_name# #userID#

</cfoutput>

Here is the qryPerson.cfc (component).

<!---This cfcomponent can be modified to alter combinations

of first and last or even first, last and userID.

But your if statement would be more complex.--->

<!---Keeping it very simple here first cones the component name.--->

<cfcomponent>

<!---The function comes next make sure it is sent to return type query--->

<cffunction name="qryPerson" access="public" returntype="query">

<!---Here is my arguement I am calling it is not requiried--->

<cfargument name="first" type="string" required="yno">

<!---Then my query it is very simple but notice the embedded

if statement. Notice that the variable says with

arguments.first ARGUMENTS is what you use inside the CFC unless

you set it to a different variable but for simplicity I pulled

it directly, which is perfectly acceptable to do.--->

<cfquery datasource="emp" name="qryPerson">

Select * from emp

<cfif isdefined("arguments.first")>

where first_name = '#arguments.first#'

</cfif>

</cfquery>

<!---Now we return the query to this cfreturn tag..

just use the name of the query.--->

<cfreturn qryPerson>

</cffunction>

</cfcomponent>

Any questions? drop me a line at frank_tudor@yahoo.com

Labels: , , , , , , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home