Friday, June 10, 2011

Default Method for component cfc - SOLVED!

I've been wanting this functionality for a *really* long time. Build a single cfc with all of the functionality for re-useability within the one file.

I am happy to day I have solved this dilemma. Look no further.

Required: Application.cfc.   (This will not work with traditional Application.cfm applications.)

First, how I came upon this solution. I discovered that when a CFC is run the Application.cfc the onRequestStart and onRequestEnd functions (methods) are processed but the actual onRequest function/method is NOT processed as it is with cfm pages. This was what prompted a small modification to the onRequestStart function processing.

In this example I have to pre-set the default method named "init". You could name it "default" or whatever you prefer, but this current implementation requires a hard-coded pre-set name. I'm curious if you can dig into an object's data and pull out a default method name. But that's for another day.

<cffunction name="onRequestStart" returntype="void" access="public" output="No">
        <cfargument name="targetpage" type="any" required="true">
        <cfif (LCASE(RIGHT(arguments.targetpage,3)) IS "cfc") AND (!structkeyexists(URL,"method"))><!--- only attempt default if no method specified --->
                <cfinvoke component="#REPLACE(REPLACENOCASE(arguments.targetpage,'.cfc',''),'/','.','ALL')#" method="init" />
                <cfabort />
                <CFCATCH type="any"><!--- FAILED<cfdump var="#cfcatch#" /> ---></CFCATCH>

        <cfreturn />

This is running on Railo. This works if a method exists in the cfc named "init" and no url method=useother exists. If the "init" method doesn't exist then the cfml engine displays the public and remote methods of the cfc as normal. No existing functionality is altered or interrupted. That is the greatest part of this implementation.

This works wonders and possibly paves the way for a mini framework if you will for self contained multi-functional pages. Ajax requests and ajax posts and processing could all be in a single cfc container file.

This was an amazing discovery and a fun implementation. This will transform my application development style.


1 comment: