For the last few weeks I’ve been working on a project that uses the Mach II, ColdSpring and Transfer frameworks for ColdFusion. This is my first “real” project using Transfer and, I have to say, I’m supremely impressed with the thought and work put into the framework by Mark Mandel. It seems every time that I come up with a question of how to do something, a quick look at the methods provided in the objects generated by Transfer reveals the answer.
The latest example came this week as we were moving more heavily into coding from the planning stages we’d been in for the most part up to now when I had an occasion to use the decorator feature built into Transfer.
If you’ve done any object-oriented development you’re familiar with the concept of building methods inside your objects to contain calculations or logic specific to that particular object. That’s easy enough to do when you are writing your own bean objects, but becomes somewhat of a problem when your bean objects are auto generated by Transfer. This is the exact situation that decorators are designed to solve. The decorator pattern “allows new/additional behaviour to be added to an existing class dynamically” (Wikipedia).
<object name="Product" table="products" decorator="components.decorators.ProductDecorator"> <id name="productID" type="numeric" generate="true" /> <!-- more properties --></object>
Using the code above, we can create a ProductDecorator.cfc in the /components/decorators folder and put any custom properties and methods that we need for the Product bean there. The really sweet part is that, when Transfer instantiates a Product object, it automatically merges any properties and methods that you create in the ProductDecorator into the generated object. So, you as the developer don’t have to do anything extra in order to access your custom methods than you would if you were accessing the methods generated by Transfer. Simply get your object as normal (via the new(), read(), getByProperty() methods etc) and the resulting object returned to you will have your methods and properties included as well.
Simple, elegant, and really slick.