Blog

Injecting Functions with WireBox

Brad Wood January 31, 2017

Spread the word

Brad Wood

January 31, 2017

Spread the word


Share your thoughts

This is a guest post by Eric Peterson.

I had a unique use-case the other day, and I wanted to share the solution with you all.

I use a custom Collection component to handle many higher-order functions like map, reduce, filter, etc. Basically, it wraps an array or a query and lets you continue chaining these functions, kind of like wrapping a value with lodash in Javascript.

The challenge comes in creating a Collection. There are a few options. The first one is creating it directly:

function test() {
	var numbers = new modules.cfcollection.models.Collection( [ 1, 2, 3, 4 ] );
}

Pretty verbose. Not very portable. It would break if the module ever changed the location of Collection internally. There are a lot of improvements to be made here.

With modules in ColdBox and WireBox, we can improve this code.

function test() {
	var numbers = wirebox.getInstance(
		target = "Collection@CFCollection",
		initArguments = { collection = [ 1, 2, 3, 4 ] }
	);
}

This code is still pretty verbose, but now it's portable. Plus, WireBox will automatically manage any dependencies inside Collection.

Personally, I still find this code pretty long. Also, it's not very descriptive. There's a method on the Collection class that handles this very use case called collect. It takes a query or an array and returns a new Collection. Using it looks like this:

component {

	property name="Collection" inject="Collection@CFCollection";

	function test() {
		var numbers = Collection.collect( [ 1, 2, 3, 4 ] );
	}

}

That's a nice step up, but there is also a weird thing here. We are injecting the Collection in to our component, which is a transient component, only to call a constructor method off of it. In other languages this might be a static method (which CFCollection has for you Lucee 5 folks, by the way). If we are in a handler, layout, or view in ColdBox, we can use an Application Helper. For our use case, I might add a method to our Application Helper like this:

function collect( collection ) {
	return application.wirebox.getInstance(
		target = "Collection@CFCollection",
		initArguments = { collection = arguments.collection }
	);
}

Now, in any handler, layout, or view we can use this collect function. Our handler now looks like this:

component {

	function test() {
		var numbers = collect( [ 1, 2, 3, 4 ] );
	}

}

That, to me, reads beautifully. It has a couple drawbacks, still. The dependency on collect is implicit. If you don't know how Application Helpers work, then it looks like magic. Also, it only works in handlers, layouts, and views. What if I want to use this in a different component?

With some help on the CFML Slack, I was pointed to a WireBox mapping destination of toFactoryMethod. With this mapping destination, the result of calling a factory function is what ends up being injected. Normally this would be used to wire up a component, like so:

// Color.cfc
component {

	function init( required string color ) {
		variables.color = arguments.color;
		return this;
	}

	function blueFactory() {
		return new Color( "blue" );
	}

}

// config/WireBox.cfc OR ModuleConfig.cfc
binder.map( "BlueColor" ).toFactoryMethod( "Color", "blueFactory" );

(There are other ways to inject that same combination as above. This is just an example.)

So, all I needed was a function that returned the collect function I showed off above. Something like:

component {

	// other methods....

	public Collection function collect( any items = [] ) {
        return new Collection( items );
    }

	public any function getCollectFunction() {
	    return collect;
	}

}

And a mapping to a factory method. Something like:

binder.map( "collect@CFCollection" )
    .toFactoryMethod( "#moduleMapping#.models.Collection", "getCollectFunction" );

And now, with these two pieces in place, we achieve our ultimate goal:

component {

	property name="collect" inject="collect@CFCollection";

	function test() {
		var numbers = collect( [ 1, 2, 3, 4 ] );
	}

}

We have our terse, readable method. We have a clear dependency being injected. And we can use that dependency in any injected component.

So, the next time you wish you could inject a function instead of a component, reach for this WireBox pattern.

Add Your Comment

Recent Entries

Hackers demand a ransom to restore data from my ColdFusion web applications!

Hackers demand a ransom to restore data from my ColdFusion web applications!

Hackers demand a ransom to restore data from my ColdFusion web applications!

Unfortunately, we often hear this message from clients who thought it would never happen to them... until it did. Some believed they could delay the expense of Implementing ColdFusion security best practices for one year, while others were tempted to put it off for just a few months. However, in today's rapidly evolving digital landscape, the security of web applications, including ColdFusio...

Cristobal Escobar
Cristobal Escobar
April 16, 2024
Ortus March Newsletter

Ortus March Newsletter

Welcome to Ortus Solutions’ monthly roundup, where we're thrilled to showcase cutting-edge advancements, product updates, and exciting events! Join us as we delve into the latest innovations shaping the future of technology.

Maria Jose Herrera
Maria Jose Herrera
April 01, 2024
Into the Box 2024 Last Early Bird Days!

Into the Box 2024 Last Early Bird Days!

Time is ticking, with less than 60 days remaining until the excitement of Into the Box 2024 unfolds! Don't let this golden opportunity slip away; our exclusive Early Bird Pricing is here for a limited time only, available until March 31st. Why wait? Secure your seat now and take advantage of this steal!

Maria Jose Herrera
Maria Jose Herrera
March 20, 2024