Switching DAO Method Calls Based Upon CFC Type
Recently I encountered a situation whereby my services API had a requirement for a single method that actually retrieved many types of items, all of which extended an object that, for example purposes, I will call just "item." The biggest obstacle was that for various reasons, nothing inside the item told you what subtype it was (which is arguably a better solution than the one provided here). Nonetheless, there was a simple solution since the object itself can tell me what type it is just by examining the metadata, and I was able to call the appropriate methods using that information. Below I have the code that allows you to do this in case you encounter a similar requirement. This example does a read based upon the CFC type, but the same can be done for create, update and delete (or whatever else really).
<cffunction name="getItem" access="public" output="false" returntype="com.stuff.item">
<cfargument name="item" type="com.stuff.item" required="true" />
<cfset var cfcType = listLast(getMetadata(arguments.item).name,".") />
<cfswitch expression="#cfcType#">
<cfcase value="specificItem">
<cfset variables.specificItemDAO.read(argument.item) />
</cfcase>
<cfcase value="anotherItem">
<cfset variables.anotherItemDAO.read(argument.item) />
</cfcase>
<cfdefaultcase>
<cfthrow errorcode="com.stuff.itemService.itemTypeNotKnown" detail="You have passed an unregistered item type" />
</cfdefaultcase>
</cfswitch>
<cfreturn arguments.item />
</cffunction>
That said, I'm more interested in the design decisions that led to this Gatekeeper of AllObjects. =)
Yeah, but he's then passing the object to the read() method of a DAO before returning it. So when it comes out, it's properties are populated.
How does it know what item to get if the item is not itself?
