ColdBox and OO, Really?

Starting at the beginning I wanted push my knowledge a little more and continue with my venture into OO. Although I can recall most of the theory from my JAVA days at University, applying some of the concepts within ColdFusion does not seem to fit and in some instances proven difficult to get my head around.

I have come to the conclusion if I want to try and apply OO concepts to ColdFusion I must not think of OO and JAVA but an adaptation of the principles of OO reborn for ColdFusion (where did that come from? lol). Anyway with that said I had an eureka moment last night, ok, it came with help from the guys on the messages boards @ houseoffusion. I posted some code not fully understand the direction I needed to go in. Using ColdBox and ColdSpring I wanted to create a 'simple' example of a login which would help me better understand how to use objects containing 'getters' and 'setters'.

As it turns out its super easy in ColdBox, so easy infact I was looking for the hidden catch! Below is what I ended up with. It shows a function that is run in my handler to process a form post from a login page.

view plain print about
1<!---Login Check--->
2<cffunction name="checkLogin" access="public" returntype="void" output="true">
3 <cfargument name="Event" type="coldbox.system.beans.requestcontext">
4 <cfscript>
5 var rc = event.getCollection();//RC Reference
6
var userBean = variables.adminUsersService.createAdminUserBean(); //Create adminUserBean
7
     var errors = "";
8     getPlugin('beanFactory').populateBean(userBean);//the magic bean machine
9
errors = userBean.validateUser();//Check For Validation Errors
10

11     if NOTT ArrayLen(errors)){//No Validation Errors
12
if (variables.adminUsersService.validateCredentials(userBean)){//Check Login Credentials Does User Exist?
13

14         variables.adminUsersService.getUserByID(userBean);//Get User Deatils, Bean Will Have The User ID
15
         variables.adminUsersService.setCurrentUser(userBean);// Setup User Session
16
         setNextEvent('dashboard.overView'); // Set the Event To Run, After Logic
17
            
18 }
19 else {
20 getPlugin("messagebox").setMessage("error", "Sorry, Username/Password not found.");
21             setNextEvent('general.index'); // Set the Event To Run, After Logic
22
}
23 }
24 else {//We Have Validation Errors Show The User A Message
25
getPlugin("messagebox").setMessage("error", "<b>The Following Validation Errors Occurred:</b><br />",errors);
26 setNextEvent('general.index'); // Set the Event To Run, After Logic
27
}
28
</cfscript>
29</cffunction>

I may not have all the principles nailed down yet, but for my first attempt I was impressed about how uncomplicated it all seemed. So lets explain what the above is doing, or maybe should I say, what I think it's doing.

The item of interest is the function called 'createAdminUserBean()' which is in my service layer, "hang on, where did you create the service?" Well, ColdBox manages this for me by allowing me to auto wire it into any handler, plug-in or interceptor. In the past I would have created my service in the init() function so it was available in the handler. In ColdBox it's just 2 extra lines of code. ColdBox using its own interceptor that will inject the dependencies I need from my object factory in this case ColdSpring by using autowire="true" and...

view plain print about
1<cfproperty name="adminUsersService" type="ioc" scope="variables" />

Ok, this assumes you have done all the leg work and setup your IOC first, which I have, so thats good ;)

adminUsersService.cfc is my service layer that everything must access first. Nothing in my application has direct access to my objects or the gateway etc. An example of my service layer could be...

view plain print about
1<cfcomponent displayname="adminUsersService" output="false">
2<!---Gets The Gateway So It Can Be Accessed Via The Service Layer--->
3<cffunction name="setadminUsersGateway" access="public" returntype="void" output="false">
4 <cfargument name="adminUsersGateway" required="true" type="salesMaxx.model.gateways.adminUsersGateway" />
5 <cfset variables.adminUsersGateway = arguments.adminUsersGateway />
6</cffunction>
7
8<!---Creates the AdminUser Bean--->
9<cffunction name="createAdminUserBean" access="public" returntype="salesMaxx.model.objects.adminUsers" output="false">
10     <cfset var bean = createObject('component','salesMaxx.model.objects.adminUsers').init(createUUID()) />
11 <cfreturn bean />
12</cffunction>
13
14<!---Get User By ID--->
15<cffunction name="getUserByID" access="public" returntype="any" output="false">
16 <cfargument name="bean" type="salesMaxx.model.objects.adminusers" required="true" />
17 <cfscript>
18 variables.adminUsersGateway.readAdminUsers(arguments.bean);
19
</cfscript>
20</cffunction>
21
22
23<!---Set Current User For Login--->
24<cffunction name="setCurrentUser" output="false">
25 <cfargument name="bean" type="salesMaxx.model.objects.adminusers" required="true" />
26         <!--- set session objects --->
27        <cflock scope="SESSION" type="EXCLUSIVE" timeout="60">
28             <cfset session.user = arguments.bean.getUserName()>
29        </cflock>
30</cffunction>
31    
32<!---Get Current Logged In User--->
33<cffunction name="getCurrentUser" output="false">
34<cfset var user = '>
35 <cflock timeout="
60" type="READONLY" scope="SESSION"><!--- Read user from session if exists --->
36 <cfif isDefined("
session.user")>
37 <cfset user = session.user>

38 </cfif>
39 </cflock>
40 <cfreturn user>
41</cffunction>
42
43<!--- Delete user from session --->
44<cffunction name="
deleteUserSession" access="public" output="false" returntype="void">
45 <cflock scope="
SESSION" type="EXCLUSIVE" timeout="60"><!--- Lock session to read and/or delete user object --->
46 <cfif isDefined("
session.user")>
47 <cfset StructDelete(session, "user")>

48 </cfif>
49 </cflock>
50</cffunction>
51
52</cfcomponent>

Since at times my service layer needs access to my gateway/DAO my first function is a setter. ColdSpring actually handles that dependence!

Back to my handler...

view plain print about
1var userBean = variables.adminUsersService.createAdminUserBean(); //Create adminUserBean

This creates my empty object ready for population. So how do I populate it? "ColdBox to the rescue" with the next line...

view plain print about
1getPlugin('beanFactory').populateBean(userBean);//the magic bean machine

You can simply tell the bean factory to do it for you! The built in plugin updates an object properties via its setters automatically from the RC scope (forms fields etc) as long as they are named the same. How cool is that?

Next I do some simple validation checks using the object (the validation checks are in the object itself which I have not show here). I am going to skip over that bit as its covered else where. I also check if the user exists so I can do the log process next. I need access to the getway/DOA for this check via the service layer, but I don't need to worry as its available thanks to ColdSpring managing my dependences!

The last 3 important lines for me are...

view plain print about
1variables.adminUsersService.getUserByID(userBean);//Get User Deatils, Bean Will Have The User ID
2variables.adminUsersService.setCurrentUser(userBean);// Setup User Session
3setNextEvent('dashboard.overView'); // Set the Event To Run, After Logic

They do a lot. Now we have a populated object I can use it to get the current user, log them in and redirect to the logged in screen.

For now I like what ColdBox and ColdSpring can do. Obviously this is a very simple example of a login and I would implement much better security using interceptors etc, but it's a start into my OO experience with ColdFusion, and I am really enjoying it :0

Related Blog Entries

Aug17

Comments 4

  1. Ben Nadel's Gravatar # Posted By Ben Nadel
    21/08/09 22:49

    I took Luis' ColdBox class at CFUnited and I have to say that I'm very impressed with it. I want to start a test project with it to really get a hang of it.

  1. Glyn Jackson's Gravatar # Posted By Glyn Jackson
    25/08/09 09:25

    Hi Ben,

    I read your blog often so I would very much like to read any results or tutorials that I assume you would write about if you did ;)

    at the moment I am only a beginner in this CF area, everything I am learning is on blogs and the ColdBox Docs which are very in depth and worth checking out.

  1. Ben Nadel's Gravatar # Posted By Ben Nadel
    06/09/09 18:13

    @Glyn,

    Hopefully I'll be able to start looking into it soon. Been behind on all my R&D stuff. But, starting to catch up now.

  1. Luis Majano's Gravatar # Posted By Luis Majano
    26/03/10 04:47

    Come on Ben!! I am waiting for you ColdBox Tutorials!!

    Great stuff Glyn!!