Thursday, June 25, 2015

Wirebox: Creating a Transient Object in a Service

Today I had the need to create a transient object outside of the normal places Wirebox lives in a Coldbox application (handlers, interceptors, etc).  I come from a ColdSpring background, so I never used CS to handle any of my transients, but I wanted to see how Wirebox handled this so I could keep my object creation centralized.

There are several ways to handle creating a transient object in a ColdFusion service.  The easiest is to use createObject() or create a new object using the new keyword right where you need it like this:

var myObj = createObject("component", "");
var myObj - new Object();

Another option is to have your service hand you a new object by defining a load() method:

public myObjectType function load () {
  return createObject("component", "");

The above method works best when using something like CF ORM, where you would specify an optional id parameter and use entityLoadByPK() and return a persistent object.  Overkill for what I need here (no persistence in this application).

What I ended up doing to keep my objects coming from a single source (Wirebox) was to inject Wirebox into my service and use the getInstance() method to hand me a transient instance of my object:


component accessors="true" {
  property name="wb" inject="wirebox";
  function myFunc () {
    var myObj = getWB().getInstance("myObject");

I figure doing it this way makes it much easier as I am presently moving around packages, so defining them once in Wirebox means I don't have to perform a search and replace once the packages settle - I just fix the path in the Wirebox configuration and all objects are updated when the application is reloaded.

Note that this works well for transient objects, but remember for singletons you would just inject them into a property in your service tier.

No comments:

Post a Comment