You are on page 1of 15

MigratingaFlashapplicationtoFlex

Author:AralBalkan
Copyright2004AralBalkan.AllRightsReserved.
ReleasedundertheCreativeCommonsAttributionShareAlike2.0England&Wales
License.

InthisarticleIwillshowyouhoweasyitcanbetomigrateawellarchitected
MacromediaFlashapplicationtoMacromediaFlex.Intheprocess,youwillseethatthe
twotechnologiesaremoresimilarthandifferentandlearnaboutbestpractices,pattern
basedmethodologiesthatlower theriskofdevelopingRichInternetApplicationsinthe
Flashecosystem.

TheFlashEcosystem
Macromediausesthetermecosystemtorefertothefamilyofproductsthatinsome
wayutilizethevirtualmachineweknowastheFlashPlayer.ThisincludestheFlashIDE
developmenttool, Flexpresentationserver andFlexBuilderdevelopmenttool.Both
FlashandFlexcanbescriptedusingtheECMAScript4basedActionScript2language
andbothproduceSWFfiles,thecompiledbytecodethatisinterpretedbytheFlash
virtualmachine. Wheretheydiffer greatly isinthesourceformatsusedandthetimeof
SWFgeneration.

TheSourceofitAll
ThefirstbigdifferencebetweenFlashandFlexisthatFlashusesabinaryFLAfileto
storeitsapplicationstructurewhereasFlexusesatextbasedonebasedonMacromedias
markuplanguageforFlex,MXML.Additionally,bothFlashandFlexcanbescripted
usingActionScript,whichitselfcaneitherbestoredaspartofanFLAorMXMLfileor
keptexternallyintextbasedclassfiles.
NothavinganyofitssourcecodeinabinaryformatgivesFlextheadvantageof being
easiertoversioncontrolanddiff(automaticallycreatealinebylinereviewofchanges
betweendifferentversionsofthesamefile.)However,asyouwillsee,therearewaysto
lessentheriskassociatedwithusingFlashsproprietaryFLAformatbyusingbest
practices,patternbasedmethodologiesinyourdevelopmentprocess.Suchanapproach
hastheaddedbenefitofmakingiteasiertoportapplicationsfromFlashtoFlex.

AMatterofTiming
ThesecondbigdifferencebetweenFlashandFlexisthetimeofSWFgeneration.
InFlash,SWFfilesaregeneratedfromthesourceFLAandActionScriptclassfilesbythe
FlashIDEatdevelopmenttime.TheseSWFfilescanthenbedeployedtostagingand
productionserversandservedlikeanyotherfilebythewebserver withoutneedfor
additionalserversideprocessing.
IntheFlexdevelopmentmodel,developersuseeithertexteditorsortheFlexBuilderIDE
tocreatetheirMXMLsourceandActionScriptclasses. Thesearethendeployedtothe
FlexserverwhichcompilestheMXMLandActionScriptfilesandgeneratesSWFfilesat
runtime.ThisoccurswhentheMXMLfileisfirstrequestedand,subsequently,whenever
theMXMLfileischanged. Bothapproacheshavetheir advantagesanddisadvantages,a
discussionofwhichisbeyondthescopeofthisarticle.
NowthatyouknowthetwomaindifferencesbetweenFlashandFlexandhavesome
perspectiveonhow thetwotechnologiesrelatetoeachother,letstakealookatasample
Flashapplicationandexplorehowitsarchitecturedeterminestheeasewithwhichyou
canmigrateitfromFlashtoFlex.

ARPPizza:FlashVersion
ARPPizzaisoneofthesampleapplicationsthatcomeswiththeAriawareRIAPlatform
(ARP)theopensource,bestpractices,patternbasedActionScript2frameworkfor
FlashandFlexbasedRIAdevelopment.Itisamakebelieveonlinepizzastorewhere
userscanorderpizzasandviewexistingorders(andallwithoutspendingasingledimeor
actuallyreceivinganypizza,forthatmatter!).
ThefrontendisbuiltinFlashandthebackendusesacombinationofPHPandMySQL.
ThecommunicationbetweenthetiersisestablishedviaAMFPHP(http://amfphp.org/),
anopensourcePHPimplementationofFlashRemoting.Infact,ARPPizzaisapattern
basedremakeoftheAMFPHPPizzaServicesampleapplication,whichyoucanfindon
theAMFPHPhomepage.

[ARPPizza:Flashversion]
Itisbeyondthescopeofthisarticletoshowyouhowtosetupyourdevelopment
environmentandinstallthevariousserversandthedatabasenecessarytobuildandrun
theFlashversionof ARPPizza.Youcandothisonyourown,ifyouwant,by
downloadingARP(http://osflash.org/ARP)andfollowingtheinstructionsinthe
comprehensiveFlashHelpmanualitcomeswith.TheFlexversionoftheapplication,
whichyoushallseelaterinthearticle,willbereleasedinthenextofficialupdatetoARP.
ThelatestprereleaseversioniscurrentlyavailablefordownloadfromtheARP
SubversionrepositoryatSourceSecure(http://svn.sourcesecure.co.uk/osflash/arp).
Insteadofprovidingastepbysteptutorial,I willhighlighttheimportantarchitectural
elementsoftheARPPizzaapplication,namelyitsformsbaseddesignandtheseparation
ofbusinessandpresentationlogicandexaminehowthesetwofactorsmakeitvery
simpletomigrateitfromFlashtoFlex.I willthentakeyouonatouroftheFlexversion,
highlightingthechanges.

Formsbaseddesign
TheARPPizzaapplicationusesaformsbaseddesignutilizinglightweight,movieclip
basedARPForms. TheARPFormclassextendsthecoreMovieClipclass usingthe
EventDispatchermixintoallowthebroadcastingofevents.
Theabilitytodispatcheventsiscentraltoimplementingloosecouplinginyour
applicationsandmakesitpossibleforyoutocleanlyseparatepresentationandbusiness
logic.(IcouldjustaseasilyhaveusedFlashMX2004ProfessionalFormsintheirplace
butIdidntneedtheadditionalfunctionality orweightinsuchasimpleapplication.)

[ARPPizzaFLA]
WhenyouopenuptheARPPizzaFLA,thefirstthingyounoticeisthatthereisnocode
anywheretobefound.Thisisveryimportant.AsImentionedearlier,theFLAisa
proprietary,binaryformatandputtingcodeinitisjustaskingfortroublebymakingyour
applicationshardertomaintainandscale.

Alsoapparentisthatthereisonlyasingleframeinthemaintimelineandthat,inturn,
containsasingleARPForm:AspecialformcalledtheApplicationform.The
Applicationformisspecialbecauseitcontains,inahierarchy,alloftheotherformsthat
togethermakeupyourapplicationsView.
ThisstructureisanaturalconstructforFlashasitresultsinchildformsgettinginitialized
beforeparentforms,allthewayupthehierarchyuntilwereachthecoreApplication
form.Amongotherthings,thisdoesawaywithhavingtocreateanadditionalstatic
main()methodorotherentrypointintoyourapplication.TheonLoad()methodofthe
Applicationformbecomesyourentrypoint.
AlloftheformsarelinkedtotheirrespectiveActionScript2classesthroughtheir
LinkageIDs.(TheApplicationForm,forexample,islinkedtothe
com.ariaware.pizza.view.Applicationclass.)
InthescreenshotoftheARPPizzaFLA,youcanseewhattheinsideoftheApplication
formlookslikeintheFlashIDE.ItcontainsaDataPreloadercomponent,whichisshown
duringdataexchanges,childformsandsomebackgroundgraphicalelements.TheOrder
formisshownasselected.

Componentware
TheOrderform,inturn,ismadeupofstandardVersion2Flashcomponents.Thisisalso
important. Apartfromprovidingastandardlibraryofcommoncomponents,theVersion
2componentsallusetheEventDispatcherandareimplementedusingtheModelView
Controller pattern.Thismakesthemideallysuitedforuseinaneventbasedsystemlike
ours.Furthermore,Flexcomponentsarebasedonthesamecodebaseanddifferonly
slightlyfromtheirFlashcounterparts.Thismakesmigrationeasier.Infact,itwouldbe
logicaltoexpectfuturereleasesofFlashandFlextobringthecomponentsclosertogether
untilwehaveasinglecomponentsetforboth.

SeparatingPresentationLogicandBusinessLogic
Soasyoucanseeinthescreenshot,theFLAinourexamplecontainstheapplications
Viewwhichisbrokendownintoahierarchyofforms,withthemainApplicationform
containingtheOrderform,NavigationformandViewOrdersform.Eachoftheformsis
linkedtoitsownclass.TheApplicationformisspecialinthat, astherootform,itactsas
theControllerfortheViewitself listeningforandrespondingtoviewrelatedevents.
Butwhataboutotherevents?Eventsthatshouldsomehowtriggerbusinesslogictobe
executedsuchaswhentheuserpressesthePlaceOrder buttontoorder somepizza?In
ARP,theseareknownasSystemEventsandweuseanApplicationControllertolisten
forthemandexecuteCommandsinresponse.

Controller,Commands,ValueObjectsandtheServiceLocator
WhentheuserpressesthePlaceOrder button,thebuttoncomponentbroadcastsaclick
event.Inresponsetothis,theplaceOrder()eventhandlerintheOrderFormgetscalled.
ThishappensbecausetheOrderFormregisteredthatmethodasalistenerwiththePlace
Orderbuttonwhentheformfirstloaded:
//ListenforthePlaceorderbuttonclick
placeOrderButton.addEventListener("click",Delegate.create(this,placeOrder))
(TheDelegateclassisanewadditioninthe7.02updaterforFlashandcausestheclick
eventtoberelayedtotheplaceOrder()method.)
TheplaceOrder()eventhandler,inturn,dispatchesaneventthatisuniquetotheOrder
Form,calledorderPizza.Themethodisshownbelow:
functionplaceOrder():Void
{
dispatchEvent({type:"orderPizza"})
}
TheApplicationform,initsroleastheControllerforthechildformsintheView,is
listeningfortheorderPizzaevent,havingregistereditselfasalistenerwhenitfirst
loaded:
orderForm.addEventListener("orderPizza",this)
IntheApplicationformsorderPizza()eventhandler,thereisjustonelineofcode:
functionorderPizza()
{
showDataPreloader()
}
ThiscausestheDataPreloadermovieclip,whichcontainsastandardindefinite
ProgressBarcomponentalongwithascreenshade/buttonblocker, todisplay.

[ARPPizzaapplicationrunningwiththeDataPreloadervisible]
Thescreenshade/buttonblockerpreventsusersfrompressingthePlaceOrderbutton
multipletimesacommonusabilityissuethatexistsinmanyHTMLbasedweb
applications.
Butwaitaminute,howdoestheclientnotifytheserverthattheuserhasorderedapizza?
TheremustbesomethingelselisteningfortheorderPizzaeventontheOrderFormand
thereis:TheApplicationController.
TheApplicationControllerlistensforSystemEventsontheViewandexecutes
Commandsinresponse.Commandscancarryoutbusinesslogicthemselves,ordeferthat
tasktoadedicatedBusinessDelegate. (Inthissimpleexample,Ichosetoforgotheuseof
aBusinessDelegate.)
InARP,theApplicationControllerissetupsothatitautomaticallymapsSystemEvents
toCommandsusingawelldefinednamingconvention.ReceivinganorderPizzaevent,
forexample,resultsinthecreationofaninstanceoftheOrderPizzaCommandclassand
thesubsequentinvocationofitsexecuteOperation()method.Thismethodisshown
below:
publicfunctionexecuteOperation()

{
//GettheOrderVO
varorderVO:OrderVO=viewRef.getOrderVO()
varpizzaService:Service=ServiceLocator.getInstance().getService(
"pizzaService")
//WecannotpasstheOrderVOdirectlysincetheserviceishostedremotelyand
//wecannotrefactorittoacceptaVO.
varpendingCall:PendingCall=pizzaService.order(orderVO.name,
orderVO.orders)
pendingCall.responder=newRelayResponder(this,"onResultOperation",
"onStatusOperation")
}
Here,youcanseethatwefirstasktheformthattheeventoriginatedon(andwhichthe
ControllerprovidedareferencetouswithintheviewRefproperty)tosendustheOrder
ValueObject.AValueObjectisnothingmorethanasingle,simpleobjectthatcontains
allthedataweneedtocarryoutaspecificunitofbusinesslogic.Inthiscase,itcontains
allthepropertiesweneedtosuccessfullyprocessanorder.BypassingaroundaValue
Objectinstanceinsteadofmultiplearguments,wemakeourapplicationeasierto
maintain.Furthermore,sincetheserversideimplementationwillhaveanidenticalValue
Object,thisformsaverystrongcontractbetweenthetiers.Membersofboththeclient
sideandserversideteamscaneasilycheckthiscontractforconsistencyatanytime.
Inthisexample,weareforcedtocallaremotemethodusingmultipleargumentsaswe
areaccessingtheoriginalbackendprovidedbytheAMFPHPexampleinsteadofour
ownlocalinstance.I decidedtoimplementitinthismannertomakeiteasierfor
developerstorunthesampleapplicationupondownloadingARPwithouthavingtofirst
installawebserver,PHP,MySQLandAMFPHPontheirdevelopmentmachines.
Ideally,theremotemethodcallwouldhavelookedlikethis:
varpendingCall:PendingCall=pizzaService.order(orderVO)
TheremotingcalliscarriedoutusingthenewFlashRemotingActionScript2APIwhich
utilizestheRelayResponderclasstorelayresulteventstotheonResultOperation()
methodandstatus(error)eventstotheonStatusOperation()method.
TocompletethechainofeventssparkedoffbytheuserpressingthePlaceorderbutton
intheOrderForm,takealookattheonResultOperation()methodthatgetscalledonce
theremotingmethodhasreturned:
functiononResultOperation(resultObj:ResultEvent):Void
{
//AlerttheViewthatthecommandexecutedsuccessfully

viewRef.orderProcessed()
}
TheorderProcessed()methodiscalledtoinformtheformthattheorderhasbeen
processed.TheorderProcessed()eventhandlerontheApplicationformrespondsby
hidingtheDataPreloaderandmakingtheViewOrderformactivesotheusercanseethat
theorderisaddedtotheirlistoforders.
functionorderProcessed()
{
hideDataPreloader()
viewOrdersFormSelect()
}

[ARPPizzaapplicationwiththeViewOrdersformshowingafteraneworderisplacd]
ThisquickrunthroughshouldbeenoughtodemonstratethefollowingFiveGolden
RulesofFlashApplicationArchitecturethatarecommontoanywellarchitectedFlash
application:

TheFiveGoldenRulesofGoodFlashApplicationArchitecture
1. TheFLAisonlyusedtolayouttheView.
2. TheViewiscomprisedofFormswhichfollowahierarchicalstructurewitha
singlerootApplicationformthatcontainschildforms.Whethertheseare
ARPFormsorFlashMX2004ProfessionalFormsoryourownamazingcreation
doesntmatteraslongastheycanbroadcasteventsandencapsulatetheir
contents.
3. Theforms,inturn, containwellencapsulatedcomponentsandthewhole
applicationpracticesacomponentwareapproachtodevelopment.
4. AllcodeiskeptexternallyintheformofActionScript2.0classes.Theformsin
theViewarelinkedtotheexternalActionScriptclassesusingLinkageIDs.
5. Thepresentationandbusinesslogicareseparatedusingwellknowndesign
patternsliketheApplicationController,Command,BusinessDelegateand
ServiceLocator.
OncewehaveaFlashapplicationthatsatisfiestheabovefivepoints,itissimpleto
migrateittoFlex.Infact,apartfromsmallchangestotheViewclassestohandle
componentAPIinconsistenciesbetweenFlashandFlex,allwehavetodorecreatethe
layoutofourformsandcomponentsinMXMLinsteadofintheFLA.

ARPPizza:FlexVersion
InmigratingtheARPPizzaFlashapplicationtoFlex,Iimplementedthefollowing
changes:
1. InsteadofhavingalltheformsinthesameMXMLfile(comparabletohavingall
theformsinthesameFLA),IchosetousedifferentMXMLfilesforeachform.
Flexmakesthiseasytodoandmodularizingyourapplicationinthiswayisabest
practice(doingthesamethingfortheFlashversionwouldhavecomplicatedthe
examplewithextraexternalformloadinglogicthatFlexhandlesautomatically.)
2. InsteadofthesimplecustomNavigationform,IusedtheprovidedLinkBar
componentinFlexandincludedthisinthemainApplicationform.(AFlash
versionofthiscomponentdoesnotcurrentlyexist.)
3. Tocreateandmanagethehierarchicalstructureofforms,IusedtheViewStack
componentinFlex.

[TheFlexversion ofARPPizzarunninginMozillaFirefox,withtheViewOrderslink
intheLinkBarcomponenthighlighted]

TheMXMLcodefor theFlexversionofthemainApplicationformlookslikethis:
<?xmlversion="1.0"encoding="utf8"?>
<pizzaView:Application
xmlns:pizzaView="com.ariaware.pizza.view.*"
xmlns:mx="http://www.macromedia.com/2003/mxml"
backgroundImage="@Embed('Graphics/design.gif')"
width="550"height="400"
marginTop="0"
marginBottom="0"

marginLeft="0"
marginRight="0"
>
<mx:Spacerheight="10"/>
<mx:LinkBardataProvider="screens"/>
<mx:ViewStackid="screens">
<pizzaView:OrdersFormid="orderForm"label="OrdersForm"/>
<pizzaView:ViewOrdersFormid="viewOrdersForm"label="ViewOrders"/>
</mx:ViewStack>
</pizzaView:Application>
Noticehow,justasitwaswiththeFLA,thereisnocodeintheMXMLfile.Puttingcode
inyourMXMLfilecanbecomejustasbadamaintenancenightmareinthelongrunas
puttingcodeinyourFLA.TheonlyplaceyourcodebelongsisinyourActionScript2
classes.
ExaminingtheXMLstructure,youwillseethatIfirstdefineacustomnamespacecalled
pizzaViewthatpointstomyviewpackageforthisapplication.Thisiswheremyform
classes(Application,OrdersFormandViewOrdersForm) reside.
InmyApplicationclass,insteadofsubclassinganARPFormoraFlashMX2004
ProfessionalForm,IsubclassthecoreFlexApplicationform:
classcom.ariaware.pizza.view.Applicationextendsmx.core.Application
ThebigdifferenceisthatinFlex,theonLoad()methoddoesnotgetcalledlikeitdoesin
Flash.Instead, youhavetooverridetheinit()methodofthemx.containers.Container
class(asuperclassofmx.core.Application)andlistenforthechildrenCreatedevent.
IvefoundthatthisisactuallyamuchmorepreciseeventthanonLoad()inFlashinthatit
unfalteringly getscalledwhenacomponentorformschildrenhavefullyloadedand
initialized(inFlashwehavetosometimesresorttoaslewofdoLater()trickstowaita
singleframebeforereferencingcertaincomponents.)
Theinit()methodthatisaddedtotheApplicationclassisshownbelow:
functioninit():Void
{
super.init()
addEventListener("childrenCreated",Delegate.create(this,onLoad))
}
Asyoucansee,tominimizecodechanges,IamrelayingthechildrenCreatedeventto
theexisting onLoad()eventhandler.

ApartfromslightchangestoaccommodatethenewLinkBarcomponent,therestofthe
classremainsthesame.
Similarly,theothertwoformssubclassmx.containers.ForminsteadofARPFormand
alsoimplementthenewinit()method.
TheViewsAPI,consistingofitspublicmethodsandevents,remainsthesame.Most
importantly,Idonthavetochangeasinglelineofcodeanywhereelseinmyapplication!
NotinmyApplicationController,notinanyofmyCommandsandnotinmy Service
Locator.Allofmybusinesslogicstaysthesame(asitshould,becausemybusinessrules
havenotchanged).TheonlythingthatIhavetochangeismy presentationlayer(View).
Thus,migratingyour wellarchitectedFlashapplicationtoFlexismerely amatterof
recreatingyourapplicationsViewinFlex.
Infact,IfoundthatthemostdifficultpartoftheprocesswastryingtogettheFlex
versiontolookassimilartotheFlashversionaspossible.Bydefault,Flexoffersa
wonderfulassortmentoflayoutcontainersthatmakebuildingfluid,resizableinterfaces
childsplay.However,ittakesabitmoredisciplineifyouhavetomakeaninterface
conformtoanexactdesignwithpixelperfectprecision.Itis,bynomeansimpossibleto
doso,however,astheaboveexampledemonstrates.
FlashtoFlexmigrationisabreeze!
Torecap,ifyouhavefollowedtheFiveGoldenRulesincreatingyourFlashapplication,
migratingittoFlexinvolvesonlythefollowingthreesteps:
1. Recreateyourformsandlay outyourUserInterfaceusingMXML.
2. ModifyyourViewclassessothatyourApplicationformextends
mx.containers.Applicationandyourchildformsextendmx.containers.Formand
implementaninit()methodonyourformstolistenforthechildrenCreated
eventandrelay ittoyouronLoad()method.
3. ImplementanychangesthatmaybenecessaryinyourViewtoaccommodate
newFlexcomponentsyouhaveaddedthatdonthaveFlashcounterparts.
Inotherwords,tomigrateyourFlashapplicationtoFlex, simplyrecreateyourViewin
FlexbecausethatisallFlexisadifferentwayofrenderingviewsforFlashbasedRich
InternetApplications.
ThishasbeenawhirlwindtourofmigratingawellarchitectedFlashapplicationtoFlex.
Ihopeithashelpedyouseethatthetwotechnologiesaremoresimilarthantheyare
differentandthatmovingfromFlashtoFlexcanbeasimpleprocess.Italsobecomes
clearthatthemostimportantelementintheFlashecosystemtoday isActionScript2.By
externalizingallcodeinyourFLAandMXMLfilesusingActionScript2andfollowing

theFiveGoldenRules,youwillensurethatyourRichInternetApplicationsareeasyto
maintainandscaleandevenmigratefromFlashtoFlex.

AralBalkan Bio
AralisfounderanddirectorofAriaware,aleadingconsultingand
trainingfirmbasedinBrighton,UKandspecializinginproviding
usabilitydesignandtesting, training,consultingandarchitecture
anddevelopmentfor FlashandFlexbasedRichInternet
Applications.HeisaMacromediaCertifiedInstructor,authorofthe
AriawareRIAPlatform,runsOSFlash.organdisdirectorofthe
LondonMacromediaUserGroup.Youcangetinformationonhis
otheropensourcetools,readtutorialsandgetthelatestFlashand
Flexnews,informationandcommentaryonhisblog,FlashAnt(http://flashant.org).

You might also like