Following up on my last post regarding Lightwire Aspect Oriented Programming (AOP), I thought I’d write up some tutorials to help people get familiaried with Lightwire itself, since I didn’t see a ton of info around. The harder part is actually getting comfortable with the concepts of dependency injection and AOP. Once you got those figured out, Lightwire is stupidly easy to use.
In this post, I’ll cover the concept of dependency injection and leave AOP for another post. Dependency injection is basically a way to ensure that your code is more loosely coupled. As it turns out, it can also make it a heck of a lot easier to use your objects. As an example, I’ll use something simple that will hopefully demonstrate the concept well. I’m going to take a simple service bean (a bean is just a CFC) and a logger bean and show different ways to make them work together. The service bean could do anything, its functionality is irrelevant to this example.
<!--- Logger.cfc --->
<cfcomponent>
<cffunction name="init" returntype="Logger">
<cfreturn this />
</cffunction>
<cffunction name="log" returntype="void">
<cfargument name="text" type="string" />
<!--- Here there would be some code to log things somewhere (a file, DB, etc.) --->
</cffunction>
</cfcomponent>
The above illustrates highly coupled components. What’s wrong with it? Technically speaking, nothing. It won’t throw errors or anything (unless I screwed up something!) But the two components are tightly coupled. Imagine if you want to change the class you use for logging? In this simple scenario, it’s pretty simple, all you need to do is change that one call, but what if you have 100 service beans and all of them use the Logger bean? It becomes a bit more painful, right? OK, OK, you could do a Find/Replace in your IDE, but you catch my drift. The other problem is that you will need to manually instantiate the logger bean in every component, which is tedious and violates the DRY principle. Finally, you sometimes want a bean to be a singleton, meaning there’s only one instance of it for the entire application. You need something to manage that.
Here’s another way to go about it (the logger component stays the same so I won’t repeat it here, assume it’s the same as the one above):
<!--- Service.cfc --->
<cfcomponent>
<cffunction name="init" returntype="Engine">
<cfargument name="logger" type="Logger" required="yes" />
<cfset variables.logger = arguments.logger />
<cfreturn this />
</cffunction>
<cffunction name="doSomething" returntype="void">
<cfset variables.logger.log("Hello world!") />
<!--- Perform more actions here, anything --->
</cffunction>
</cfcomponent>
<!--- ServiceFactory.cfm --->
<cfcomponent>
<cffunction name="init" returntype="ServiceFactory">
<cfreturn this />
</cffunction>
<cffunction name="getService" returntype="Service">
<cfif NOT structKeyExists(variables, "service")>
<cfset variables.service = createObject("component", "Service").init( createObject("component", "Logger").init() ) />
</cfif>
<cfreturn variables.service />
</cffunction>
</cfcomponent>
Using the above, things are a little better. The Service bean receives the Logger bean when created and doesn’t have to worry about how it gets instantiated. However, you’re still left with the tedious task of creating the factory, instantiating the Logger manually, etc. Imagine if you wanted the logger to behave similarly. You’d have to create a factory for it to. And imagine if the logger object had dependencies of its own. You can see how this can get really ugly. That’s when a dependency framework comes to the rescue. Here’s how you would do things with lightwire:
<!--- BeanConfig --->
<cfcomponent extends="lightwire.BaseConfigObject" hint="A LightWire configuration bean.">
<cffunction name="init" output="false" returntype="any" hint="I initialize the config bean.">
<cfset addSingleton("cfcPath.Service", "Service") />
<cfset addSingleton("cfcPath.Logger") />
<cfset addConstructorDependency("Service", "Logger") />
<cfreturn this />
</cffunction>
</cfcomponent>
<!--- index.cfm --->
<cfset config = createObject("component","cfcPath.BeanConfig").init() />
<cfset lightwire = createObject("component","lightwire.LightWire").init(config) />
<cfset service = lightwire.getBean("Service") />
In the example above, assume that Logger.cfc is the same as the first example and Service.cfc is the same as the second example. With that out of the way, here’s what’s happening in the above. In the configuration bean, you’re giving Lightwire the definition for your beans. The addSingleton() function is used to define a singleton bean, and you could use addTransient() in the same way to define a transient bean. Within that function call, you specify the path of the component in the first argument and the name of the bean as the second. If the name of the bean is the same as the last part of the path, you don’t need to specify it. You then use the addConstructorDependency() to wire the beans together. The first argument is the bean you want to inject something into, the second is the bean to inject. Then the index.cfm file shows how to start Lightwire and get a bean from it. So the getBean() call basically retrieves a bean based on the configuration above. So behind the scene, something is happening to do createObject(“component”, “cfcPath.Service”).init(createObject(“component”, “cfcPath.Logger”).init()); without you having to type all that. Imagine how useful that is when you have tons of beans with lots of dependencies, that are reused in many other beans. Priceless. Note that since we defined the beans as singletons Lightwire will only instantiate them once in its lifetime. So if you store Lightwire in a persistent scope, like the application scope, your beans will only get created once, saving you the overhead of creating them over and over.
There are 3 ways to inject beans in Lightwire. The first is the one described above, using a constructor dependency. In that case, you add an argument to your bean’s init() function matching the name of the bean to be injected (or you can specify a different name as the third argument of the addConstructorDependency() function). A second way is a setter injection. For a setter injection, you would use addSetterDependency() function. The arguments are the same as for the constructor function, but to get the bean injected you need to define a method in the receiving bean named “set[BeanName]“. Finally, there’s mixin injection. You can add a mixin dependency by using the addMixinDependency() function, which works exactly like the other two, the difference is you don’t need to do anything in the receiving bean. The injection will be done behind the scenes and you don’t have to worry about a thing.
How do you know which injection type to use? It really depends. If you have two beans that both depend on each other, you can’t use constructor dependency, otherwise you’ll run into a circular reference problem. So you can use setter or mixin dependencies in those cases. If you need to use the injected bean in the init() method of the receiving bean, you’ll probably want to use constructor injection. Then it’s down to preference. Some people don’t like mixin injection because they feel it hides part of the implementation and can be confusing to an outsider looking at your application. But I find it invaluable, saves me from adding all those constructor arguments or setter methods. When I have a bean I want to inject pretty much everywhere (like a Utility bean, for example), I usually use mixin injection.
You can also inject regular properties using addConstructorProperty(), addSetterProperty(), and addMixinProperty(). All those take 3 arguments, the name of the bean, the name of the property, and the value of the property.
So this ought to cover the basics of DI and how to use Lightwire for that purpose. Stay tuned for a post on Lightwire and AOP (I’ve already done one, but I’m gonna try to make one that’s actually clear!)