View History | PDF | SWF | HTML

How do I inject dependencies into a TransferObject?

To inject dependencies into a TransferObject, the 'afterNew' event must be used.

To register an Observer for the afterNew event:

observer = createObject("component", "InjectorObserver").init(); 

getTransfer().addAfterNewObserver(observer); 

The observer must have a method on it that looks like, which is run when the event is fired:

<cffunction name="actionAfterNewTransferEvent" hint="Do something on the new object" access="public" returntype="void" output="false">
    <cfargument name="event" hint="" type="transfer.com.events.TransferEvent" required="Yes">
</cffunction>

The event is then fired *after* the TransferObject is init()'d and the configure() method is run.

So if you now want to inject something into a TransferObject, you will need to write a setter/getter on it - and you can do it something like this:

<cffunction name="actionAfterNewTransferEvent" hint="Do something on the new object" access="public" returntype="void" output="false">
    <cfargument name="event" hint="" type="transfer.com.events.TransferEvent" required="Yes">
    <cfif arguments.event.getTransferObject().getClassName() eq "user.User">
         <cfset arguments.event.getTransferObject().setService(getService()) />
    </cfif>
</cffunction> 

A <cfcase> statement could be used instead of an <cfif> depending on your needs.

You could put this event directly on a Factory of some description if you wanted to, or have it on a specific object whose only task is to inject new TransferObjects with dependencies, depending on your application design.

Categories: