How ColdSpring Implements AOP using a Decorator
During the AOP BOF session last week at CF United, he explained how he’d implemented AOP using a decorator. It’s a great example of a practical use of the design pattern and may be a good primer for anyone who wants to consider other ways of implementing AOP in CF.
Basically, a decorator is a class that wraps another class, exposing the same interface, but adding additional behavior. From the GoF summary, the decorator allows you to "attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality".
Why would I care? Well, imagine that you have a bunch of classes you'd like to add logging to. You want to run some simple logging code on the execution of each method (or all methods matching a certain criteria). You could add the code to each method, but that lowers cohesion (why should a user service have to know about logging) and decreases maintainability (what happens when you want to change the way you do your logging).
With a decorator, you can wrap the class, replicating, intercepting and extending each method call. Conceptually the code would be something like:
<cffunction name=”doSomething”>
CODE TO DO SOMETHING
</cffunction>
<!--- In the decorator --->
<cffunction name=”doSomething”>
<cfscript>
class.doSomething(arguments);
logclass.logCall(arguments);
</cfscript>
</cffunction>
In ColdSpring, there are various AOP methods which can add code before, after, around and/or on error to a set of methods, but the basic principle is that ColdSpring takes your class (say UserService) and automagically wraps it with another proxy class exposing the same interface (methods, arguments and return types) so the proxy gets called by your code and can add your advice (that is the code you want to add to the various methods) before, after or around the original method call.
ColdSpring does a great job of this, so I can’t think why you’d write this yourself, but I wanted to write an article on creating an "in class decorator" using mixins and figured this would be a useful backgrounder.
Please check out the framework and let me know what you think. Wherever you have cross cutting concerns (logging and security are the obvious examples, but workflow is another example) it is a great solution to consider. Dave Ross even showed an example in his ColdSpring presentation of a caching system that allowed you to switch off your database and keep your application running using AOP - very cool indeed.



Many thanks for the clarification! Looking forwards to playing with this stuff in the near future!
Best Wishes,
Peter