Day two with FW/1
Playing around with FW/1 today I decided to take a look at the differences at how services differ from working with domain objects. Skimming through the FW/1 documentation I did notice the framework has a built in function to populate a bean, namely the fw.populate() function. Calling a bean (an object with getter/setter methods) is not much more involved in calling a service. First, you create an instance of your bean. Then call populate() method passing rc keys that you would like to set and the populate function will find the setX method in the bean and set the appropriate value.
I have an extremely simple application I have setup that has two views. The default view is just a form that gets posted to the main.submit action which is just cfdumping the rc scope.
The sample “bean” setup for testing purposes:
<cfcomponent> <cffunction name="init"> <cfscript> variables.instance = structNew(); instance['fw'] = arguments.fw; </cfscript> </cffunction> <cffunction name="setFirstname"> <cfscript> instance['firstName'] = arguments.firstName; </cfscript> </cffunction> <cffunction name="setLastname"> <cfscript> instance['lastName'] = arguments.lastName; </cfscript> </cffunction> <cffunction name="saveUser" returntype="struct"> <cfscript> var response = structNew(); response['message'] = "Saving user: " & instance.firstName & " " & instance.lastName; </cfscript> <cfreturn response/> </cffunction> </cfcomponent>
Nothing too complicated going on here, just a basic init method to setup the instance variables, two setter methods and finally a method for “saving” our user information. The controller method for handing the submit is as follows:
<cffunction name="submit"> <cfargument name="rc" type="struct"/> <cfscript> var userObj = createObject("component", "model.user"); variables.fw.populate(userObj, "firstName,lastName"); structAppend(rc, userObj.saveUser()); </cfscript> </cffunction>
This creates the user object, populates the values and then saves the user and appending the results into the rc scope. Services are a little easier to implement as they have a one line invocation. I am still trying to figure out when it would be best to use a service to move data in and out of the application as opposed to creating a bean in the model. I would imagine the ultimate answer would be whatever works best for you, but I can see where services could be advantageous as well. I welcome any comments.