Wednesday, November 11, 2009

ORM Event Handling in ColdFusion 9

I've been playing around with ORM event handling in ColdFusion 9. For my application, I want to be able to fire events during various points in the lifecyle of my persistent entities. However, I don't want to have to clutter up my business logic with tasks such as logging, synchronizing integration data, or pushing changes out to Flex. I want to take a more AOP-style approach.

To do this, I created an XML-driven EventManager to use as my application's global event handler. With my EventManager, I'm able to configure listeners to respond to events fired by my entities using the built in ORM event handlers. The events can be registered using regular expressions and all follow the pattern {EntityName}:{EventHandler}. For example, I might have User:postUpdate or Product:postDelete.

In my sample application, I've configured my EventManager to send an email before and after any entity is loaded, inserted, updated, or deleted. In other words, basically anytime something happens to an entity. I'm not sure how useful this would be, but it's just an example.

Here's the directory structure:


component { = "Sample";
this.datasource = "Sample";
this.mappings["/sample"] = getDirectoryFromPath(getCurrentTemplatePath());

this.ormEnabled = true;
this.ormSettings.dbcreate = "update";
this.ormSettings.eventHandling = true;
this.ormSettings.eventHandler = "";

public void function onApplicationStart() {

application.beanFactory = createObject("component","coldspring.beans.DefaultXmlBeanFactory").init();





component implements="cfide.orm.IEventHandler" {

public void function preLoad(any entity) {

public void function postLoad(any entity) {

public void function preInsert(any entity) {

public void function postInsert(any entity) {

public void function preUpdate(any entity, struct oldData) {

public void function postUpdate(any entity) {

public void function preDelete(any entity) {

public void function postDelete(any entity) {

private void function handleEvent(any entity, string handler) {

var collection = {};
collection.entity = ormGetSession().getEntityName(entity); = entity.getID();
collection.handler = handler;

var eventManager = application.beanFactory.getBean("eventManager");




component accessors="true" {

property configPath;

public any function init() { = {};
variables.loaded = false;

public void function setConfigPath(required string configPath) {

if(fileExists(configPath)) {
variables.configPath = configPath;
else {
variables.configPath = expandPath(configPath);


public void function dispatchEvent(required string event, struct data) {

if(!structKeyExists(arguments,"data")) { = {};

if(!variables.loaded) {
variables.loaded = true;

local.listeners = getListeners(event);

for (var i=1;i <= arrayLen(local.listeners);i++) {

local.bean = application.beanFactory.getBean(local.listeners[i].bean);



private array function getListeners(required string event) {

if(!structKeyExists(,event)) {

local.used = {};

local.listeners = [];

for (var i=1;i <= arrayLen(variables.config);i++) {

if(reFindNoCase(variables.config[i].name,event)) {

for (var j=1;j <= arrayLen(variables.config[i].listeners);j++) {

local.listener = variables.config[i].listeners[j];

if(!structKeyExists(local.used, {

local.used[] = true;




}[event] = local.listeners;




private void function loadConfig() {

variables.config = [];
local.xml = xmlParse(fileRead(getConfigPath()));

for (var i=1;i <= arrayLen(;i++) {

local.event = {}; =[i];
local.event.listeners = [];

for (var j=1;j <= arrayLen([i].xmlChildren);j++) {

local.listener = {};
local.listener.bean =[i].xmlChildren[j].xmlAttributes.bean;
local.listener.method =[i].xmlChildren[j].xmlAttributes.method; = local.listener.bean & "." & local.listener.method;







component {

public void function sendNotification() {

savecontent variable="local.body" {

var notification = new Mail();





<bean id="eventManager" class="">
<property name="configPath">

<bean id="notificationService" class="" />



<event name="[\w]+:(pre|post)(Load|Insert|Update|Delete)">
<listener bean="notificationService" method="sendNotification" />

I'm not sure if this is the best approach or how well this would scale, but it seems to work pretty well for now.

PS - note the use of savecontent inside script. And they said it was pointless... :)

Tuesday, November 10, 2009

ColdFusion 9 Mail in cfscript

I ran into an issue today trying to send an email using script syntax. My code was pretty simple:

var email = new Mail();
email.setSubject("Test Email");
email.send(body="Hello, world");

However, when I tried running the code, I got the following error:

Could not find the ColdFusion component or interface Mail.

While it's pretty obvious now what the problem is now, at first I was pretty confused. I figured since all the tags were converted to handle script syntax, everything should just work. I checked the ColdFusion 9 documentation and everything looked fine. After about 10 minutes I finally figured it out.

When installing ColdFusion, one of the first things I do is clean up ColdFusion Administrator by removing the default datasources and custom tag paths. However, when Adobe added script support for a couple tags (ftp, http, mail, pdf, query, storedproc), they chose to implement the functions as objects using CFCs. When I deleted the default custom tag path, ColdFusion was no longer able to find the Mail.cfc, since it was relying on the custom tag path.

If you go to cf_root\servers\cfusion\cfusion-ear\cfusion-war\WEB-INF\cfusion\CustomTags\com\adobe\coldfusion\, you should see all the tags implemented as CFCs. Kinda interesting.

On a random note, although it was said that <cfsavecontent /> would not be implemented in script syntax, apparently it was. You can see it in action if you view the examples on the documentation for using mail in script.

savecontent variable="mailBody"{
WriteOutput("This message was sent by...");