I thought I could write a tutorial for creating a basic coldfusion web service illustrating the possibilities of using reusable component rather than having lots of queries retrieving (in most of the cases) the same data.

Let's say there are 5 articles in a B&O database, each time the article is visited, a DB field visited is increased by 1 (obviously only once for 1 unique IP address). For instance the article Multiple Files Upload has been visited 290 times, Easy and secure way to retrieve data from a database (340) and Creating a newsfeed generator was visited 95 times.

We may create a coldfusion reusable component to get the most popular link along with some different stuff such as total number of vists etc:

<cfcomponent displayname="Web Service CFC Example">

//get a total_visits value for every article in a database
<cfquery name="get_visits" datasource="#DSN#">
SELECT article_title, total_visits FROM articles

<cfproperty name="name" type="string">
<cfset this.name="Web Service CFC Example">

<cffunction name="totalVisits" access="public" returntype="numeric">
<cfset total="0">
<cfloop query="get_visits">
<cfset total = total + #visits#>

<cfreturn total>

//check, which article is the most popular
<cffunction name="winningArticle" access="public" returntype="string">
<cfset maximum = 0>
<cfset winner = "unknown">

<cfloop query="get_visits">
<cfif #visits# gt maximum>
<cfset maximum = #visits#>
<cfset winner = #article_title#>

<cfreturn winner>


It's worth to mention, that I might add an additional function in above component that returns the results as a structure (preferable way), in such case you would need to incorporate following code. I am going to write an additional tutorial explaining in detail how to use CFC structures.

<cffunction name="allResults" access="public" returntype="struct">
<cfset all = structNew()>
<cfloop query="get_visits">
<cfset result = structInsert(all,#article_title#,#visits#)
<cfreturn all>

The structure is basically a collection of data which is a bit more complex than a simple string or number.

Now, as the component is created, here's a way to call it and retire the result.


Total visits:
<cfinvoke component="articles.cfc" method="totalVisits"


The most popular article:

<cfinvoke component="articles.cfc" method="winningArticle"


Tagged: coldfusion  web service