explorers’ club


ServiceLocator Quick Tip
Friday, December 21, 2007, 5:55 pm
Filed under: actionScript, cairngorm, development, flex

Depending on your services setup, and if you use Cairngorm, you have probably seen or written alot of code like this:

public function execute (event:CairngormEvent):void {
var call:AbstractOperation = ServiceLocator.getInstance().getWebService("someName").getOperation("someOperation");

So suppose you have many WSDLs or if you are like me and are using AMFPHP, you might have quite a few Remote Objects logically split up. For instance, you might have 6 RemoteObjects in your ServiceLocator subclass mxml. Like so:

<?xml version="1.0" encoding="utf-8"?>
<adobe:ServiceLocator
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:adobe="http://www.adobe.com/2006/cairngorm">

<mx:RemoteObject id="userServices" source="userServices" destination="amfphp" showBusyCursor="false"/>
<mx:RemoteObject id="journalServices" source="journalServices" destination="amfphp" showBusyCursor="false"/>
<mx:RemoteObject id="adminServices" source="adminServices" destination="amfphp" showBusyCursor="false"/>
<mx:RemoteObject id="activityServices" source="activityServices" destination="amfphp" showBusyCursor="false"/>
<mx:RemoteObject id="miscServices" source="miscServices" destination="amfphp" showBusyCursor="false"/>

</adobe:ServiceLocator>

I like being able to code quickly and know that I am pointing to the correct RemoteObject without a) having to look at the mxml to get the right name or b) hope that I remember what I called it. In order to do so I added a few lines of code in my <script/> tags to my ServiceLocator subclass named ApplicationServices.mxml:

public static function getInstance ():ApplicationServices {
return ApplicationServices(ServiceLocator.getInstance());
}

Now when I am quickly making command classes that I want to ensure use a particular RemoteObject without relying on the getRemoteObject() method and my fuzzy memory of what was named I can type:

public function execute (event:CairngormEvent):void {
var call:AbstractOperation = ApplicationServices.getInstance().userServices.getOperation("someOperation");

I think this is a bit cleaner and nicer looking.  And its just one less step to have to remember or reference when creating your commands.