ColdFusion Component Setters / Accessors Are Chainable For Easy Dependency-Injection
This is primarily a note-to-self; but the other day, I stumbled upon / remembered that the auto-generated accessors in a ColdFusion component are chainable. At work, I never think about this because we use a dependency-injection framework which performs all the setter-injection for us. However, in my blogging platform, all the components are wired-up manually in my onApplicationStart()
event-handler. As such, the fact that I can chain my setter accessors leads to a lovely, fluent API.
To see this in action, here's a simple ColdFusion Component that has accessors=true
and a few CFProperty
tags:
component
accessors = true
output = false
{
// Define properties for dependency-injection.
property logger;
property myGateway;
property stats;
// .... we're just focusing on accessors in this demo .... //
}
With accessors=true
on the CFComponent
tag, ColdFusion will automatically generate both a getter and a setter for each of the CFProperty
tags:
getLogger()
setLogger( logger )
getMyGateway()
setMyGateway( myGateway )
getStats()
setStats( stats )
All of the set{name}()
methods can be chained:
<cfscript>
fakeGateway = { displayName: "fakeGateway" };
fakeLogger = { displayName: "fakeLogger" };
fakeStats = { displayName: "fakeStats" };
// Note that our SETTERS can be chained for easy dependency-injection.
myService = new MyService()
.setLogger( fakeLogger )
.setMyGateway( fakeGateway )
.setStats( fakeStats )
;
cfdump( var = myService );
</cfscript>
As you can see, each the setter methods returns the ColdFusion component instance. Which means, each setter can be chained on the previous setter; and, the last setter call can then store the resultant value into a component reference variable.
When we run this ColdFusion code in Lucee CFML, we get the following output:
As you can see, there are 6 generated accessors for the 3 properties. And, the "fake" dependencies that we injected show up as the property values. Internally, these properties have been stored into the private variables
scope of the ColdFusion component.
For large ColdFusion application, some sort of Inversion of Control (IoC) container should be used (think Framwork/One, think WireBox); but, for small sites, manually dependency-injection (DI) is more than sufficient. And, being able to chain setters is a lovely little property (no pun intended) of the language.
Want to use code from this post? Check out the license.
Reader Comments