Sean Corfield pointed out that using ColdSpring to make instance (throwaway) components is quite a heavyweight approach for a simple form bean. He is, of course, correct. Our ContactFormBean is currently created by ColdSpring. In this series, we will add a factory object that will make our instance beans for us. The factory itself will be configured through ColdSpring as well as the configuration for our objects.
This is a very simple factory. It has three methods, GetConfig, SetConfig and getBean. In turn:
- getConfig() returns a struct with keys = objectnames, and values = paths
- setConfig() provides an interface for ColdSpring to set the configuration struct.
- getBean() gets the path for a specific object from the configuration struct and returns a created object.
<!--- Author: dwilson Date: 3/14/2007 Usage: I return an instance object --->
<cffunction name="getBean" output="false" access="public" returntype="any" hint="I return an instance object">
<cfargument name="ObjectName" type="string" required="true"/>
<cfreturn createObject( "component", structFind(getConfig(), arguments.ObjectName ) ).init() />
<cfthrow message="BAD_OBJECT_CONFIG_IN_INSTANCEFACTORY" detail="You provided [ #arguments.ObjectName # ] and I can't create it. Go check the config." />
<!--- Usage: GetConfig / SetConfig methods for Config value --->
<cffunction name="getConfig" access="public" output="false" returntype="any">
<cfreturn variables.instance.Config />
<cffunction name="setConfig" access="public" output="false" returntype="void">
<cfargument name="Config" type="any" required="true" />
<cfset variables.instance.Config = arguments.Config />
To use this instance factory, add the following ColdSpring xml snippet to the ColdSpring.xml file.
Now remove the original ContactFormBean configuration.
Next, open the Controller.cfc file and change each instance (getContactForm, handleContactForm and removeContact) of getModelGlue().getBean("ContactFormBean") to getModelGlue().getBean("InstanceFactory").getBean("ContactFormBean") .
Finally, reinitialize your application and click on the ContactForm tab. You should see your form as before.
A factory might seem like overkill right now, since this is a simple application. However, Factory objects are a good pattern to learn. Our motivation for the factory in this case was to reduce the amount of unnecessary processing incurred by using ColdSpring to make a simple form bean. We could however, expand our factory to take additional parameters and create all sorts of dynamic objects for us.
In a later series, we'll do just that.