28 April 2013

Building a CF SOAP Webservice

I recently needed to create a web service which pleased me as its very easy with coldFusion.

Although, that said, one thing that has often puzzled me is the Application.cfc and the cfc initialization. You probably wouldn’t want to use your normal Application.cfc as it’s likely a bit excessive. To my mind webservice requests could take place weeks apart, or just minutes and should be lightening fast, so a very lightweight initialization process would be ideal.

Lets assume a very basic webservice.cfc:

<cfcomponent output="false">
    <cffunction name="getUsers" access="remote" returnType="query" output="false" hint="I get some users">
        <cfreturn application.oUsers.getUsers() />

So oUsers is our DAO or Business object which we use in our application. Normally it would be passed in with an init method, but with a webservice we don’t have the same concept of init’ing objects. So how does one go about initializing our DAO? In the past I’ve seen many takes on this. I’ve seen:

In the method:
<cffunction ...>
    <cfset var oUsers = createObject(...)>
    <cfreturn var oUsers.getUsers()>

In the actual webservice.cfc, scoping it this/variables/application
<cfcomponent output="false">
    <cfset variables.oUsers = createObject(...)>
    <cffunction ...

Both of the above involve the dao cfc being re-created on every web-service request. Not exactly ideal in terms of performance.

So I think the best idea I’ve seen so far is create an application.cfc like so:

<cfcomponent output="false">
    <cfset this.strDsn            = "mydsn" />
    <cffunction name="onApplicationStart" access="public" returnType="boolean" output="false">
        <cfset application.oUsers    = createObject("component","usersDao").init(strDsn    = this.strDsn) />
        <cfreturn true />

This gives a lightweight application scope in which we can initialize our object and then call throughout our webservices! Excellent!

If you’ve got any suggestions on how to improve this, please feel free to comment.