Upload
ntunney
View
935
Download
1
Embed Size (px)
DESCRIPTION
Presentation on getting started with the Swiz framework for Adobe Flex. It concentrates on solving problems around IoC, dependency injection, event handling and interacting with external services.
Citation preview
1
Introduction to Swiz
It’s easy. Seriously. No, I mean it. It is.
Nicholas Tunney
2
Session Goals
• What problems are we trying to solve?• How do I set up Swiz?• How do I put Swiz to work for me?• Where else can I learn about Swiz?
3
WHAT PROBLEMS ARE WE TRYING TO SOLVE?
4
Inversion of Control
• Decentralize application control• Provide for actions on setup and teardown• Separate the WHAT from the WHEN
5
Inversion of Control
DANGER!
Cour
tesy
of J
oam
Tal
l (Fl
ickr
)
6
Dependency Injection
• Objects are dependent on other objects• Objects need those objects to be created
(instantiated) to perform a task• Objects that handle their own object creation
are said to be ‘tightly coupled’• A simple change to the program results in
major code changes, just not flexible• Problem is best illustrated with an example
7
Dependency Injection
public class Boat {private var engine:Engine = new Merc230();
public function boat () {}
cruise (int RPM):String {engine.go(RPM);return engine.thrillFactor;
}}
8
Dependency Injection
public class Boat {private var _engine:Engine;
public function boat () {}
set Engine (engine:Engine):void {_engine = engine;}
cruise (int RPM):String {_engine.go(RPM);return _engine.thrillFactor;}
}
9
Dependency Injection
myBoat:IBoat = new Boat();myEngine:IEngine = new Merc230();myBoat.setEngine(myEngine);myBoat.go(3000) // ‘w00t!’myNewEngine:IEngine = new Merc57();myBoat.go(3000) // ‘YEEEHHHHHAAAA!!!’
10
Dependency Injection
• Can see how powerful dependency injection can be
• Can do that in various places across files (still lots of code to change, or via configuration using a framework like Swiz (one file to change)
11
Singletons
• Create once, use everywhere• Low overhead, single instantiation
• Swiz is used to create these objects, and handle keeping state across the application
12
Creation of Transient Objects
• Swiz permits Prototyping objects• Acts like an object factory• Ask Swiz for an object, it injects dependencies
and hands you a single instance of that object• Not persistent
13
Event Handling
• We react to events in the application and perform tasks (WHAT versus WHEN)
• Event handling in Flex can be a nightmare challenge• Events need to be dispatched from non-display objects to
varied display objects• Events need to be dispatched from display objects to non-
display objects like controllers or their presentation models• I want to fire an event ANYWHERE in my Flex application,
and mediate it ANYWHERE in my Flex application
14
Interaction with External Services
• Every Flex app I have written (except 1) has interacted with external services, it’s the way of the web anymore
• Each external service call has a set signature and workflow
• Writing this workflow for every call is tedious, or moreover redundant
15
HOW DO I SET UP SWIZ?
16
Grab the SWC
• http://www.swizframework.org• Place correct swc in /lib directory
17
SwizConfig
• Brutally simple, just like the framework• Can simply copy/paste• A few knobs to turn
18
SwizConfig
<swiz:config> <swiz:SwizConfig setUpEventType="{ Event.ADDED_TO_STAGE }" setUpEventPhase="{ EventPhase.CAPTURING_PHASE }" setUpEventPriority="50" tearDownEventType="{ Event.REMOVED_FROM_STAGE }" tearDownEventPhase="{ EventPhase.CAPTURING_PHASE }" tearDownEventPriority="50" eventPackages="com.foo.event.*, org.bar.event.*" viewPackages="com.foo.view.*, org.bar.view.*" defaultFaultHandler="handleUnhandledFaults" defaultDispatcher="global" /> </swiz:config>
19
SwizConfig
<swiz:config> <swiz:SwizConfig eventPackages="com.foo.event.*, org.bar.event.*" viewPackages="com.foo.view.*, org.bar.view.*” /> </swiz:config>
20
Logging Target
• I do not write perfect code, I need to log – a lot• Built in logging for Swiz to console• Can override and customize by extending the
AbstractSwizLoggingTarget class
<swiz:loggingTargets> <swiz:SwizTraceTarget id="myTraceTarget" /> </swiz:loggingTargets>
21
Stuff We Didn’t Do
• Verbose configuration• Force the usage of J2EE patterns• Have to define any special directory structure• Tightly couple Swiz to our code (except with
ServiceHelper and command chain) – no extending framework classes, etc)
• Take more than 5 minutes to review the Quickstart ;)
22
HOW DO I PUT SWIZ TO WORK FOR ME?
23
Review of Problems We Are Solving
• Inversion of Control• Dependency Injection• Singletons• Creation of Transient Objects (Factory)• Event Handling• Interaction with External Services
24
Inversion of Control
• Permits us to define and declare dependencies:– Controllers – for server interaction– Model– Delegates– Services
25
Dependency Injection
• IoC container is defined by BeanProviders– Define non-view classes– Once defined, they can all be injected into your UI,
presentation model, controllers, etc• Can define in main application file, best
practice to define and include <- but Swiz doesn’t try to force you to do this ;) - Use the <swiz:Bean /> tag
26
Dependency Injection
• Beans.mxml – or whatever you call it<swiz:BeanProvider xmlns:swiz=" xmlns:service="org.swizframework.quickswiz.service.*" xmlns:controller="org.swizframework.quickswiz.controller.*"> <service:UserService id="userService"/> <controller:UserController id="userController"/> <!-- We'll use the Swiz ServiceHelper to help simulate a server-side call. --> <swiz:ServiceHelper id="serviceHelper" /> </swiz:BeanProvider>
27
Dependency Injection
• So how do we inject these objects? METADATA!(Note that Swiz can inject into public properties only)
– Inject by type (preferred)[Inject]variableName:Type
– Inject by name[Inject (“myService”)]variableName:RemoteObject;
28
Dependency Injection
Can also inject a bean property[Inject (“ApplicationConfig.mode”)]currMode:String;
Or provide a destination[Inject ( source=“ApplicationConfig.mode”,
destination=“presentationModel.mode” ) ]
29
Dependency Injection
Setter Injection is also possible
[Inject]public function setModel (model:UserModel):void {
…}
30
Singletons
• All objects created in the beans.mxml as described are officially singletons
• This statement is not true for prototype objects
BEAN LIFECYCLE
31
Bean LifeCycle
• [PostConstruct]• [PreDestroy]
Type Step
Flex Removed event
Flex Removed from stage event
Swiz [PreDestroy] processed
Swiz [Inject] tear down
Swiz [EventHandler] tear down
Swiz [Dispatcher] tear down
Swiz Default custom metadata tear down
Swiz [ViewRemoved] processed
32
Creation of Transient Objects
• New object created for each request• Much like an object factory• Can send in properties via configuration as
well<swiz:Prototype id=”User" type="{ User }" constructorArguments="{ someOtherBean }" />
33
Event Handling
• Event mediation – decouples the WHAT from the WHEN– Code the WHAT– Wire the WHEN
34
Event Handling
• Two things we care about– Dispatching events– Mediating events
35
Event Handling
• Dispatching Events– From a UIComponent• dispatchEvent()
– important! The event must bubble!– Swiz listens in the root container
– From other objects• Inject a dispatcher
– [Dispatcher]– Variable should have a type of IEventDispatcher– Swiz handles the dependency injection
36
Event Handling
• Mediating Events– Sooooooo easy!– This was my aha moment for using a Flex
framework
37
Event Handling
• Simple Event Mediation– We can do this since we defined event packages– Otherwise, specify fully qualified classname
[EventHandler( event=“EventClass.EVENT_CONSTANT” )] public function myEventHandler (event:Event): void { … }
38
Event Handling
Swiz inspects the handler and reacts accordingly(note there is no event property in this method)
[EventHandler( event=“EventClass.EVENT_CONSTANT” )] public function myEventHandler (): void { … }
39
Event Handling
Grab properties from the event(note that we can now explicitly call this method outside of an event)
[EventHandler( event=“MyEvent.EVENT”, properties=“user” )] public function myEventHandler (user:User): void { … }
40
Event Handling
Mediate multiple events with the same handler
[EventHandler( event=“MyEvent.EVENT”] [EventHandler( event=“MyEvent.OTHER_EVENT”] public function myEventHandler (): void { … }
41
Interaction with External Services
• Swiz provides beans for Async and other services– Async: ServiceHelper– Non Async: URLRequestHelper
42
Interaction with External Services
• ServiceHelper– Define the bean– Inject the bean– Call the service– Handle the results
43
Interaction with External Services
Define the ServiceHelper bean<swiz:ServiceHelper id="serviceHelper" />
Inject the bean[Inject]
public var sh:ServiceHelper;
Call the servicesh.executeServiceCall(ro.method(), resultHandler, faultHandler);
44
Demo
Demonstrates everything we have talked about today, plus supports the Cat Internet meme.
45
Bonus: Client Persistence
SharedObject - Provides methods for storing items
<swiz:BeanProvider xmlns:swiz=" xmlns:storage="org.swizframework.storage.*”> <storage:SharedObjectBean id="soBean" /></swiz:BeanProvider>
46
Bonus: Client Persistence
Using the SharedObject bean
[Inject]public var so:ISharedObjectBean; [Bindable]public function get appIndex():int{ // the second parameter is the initial value return so.getInt("appIndex", 0);} public function set appIndex(index:int):void{ so.setInt("appIndex", index);}
47
WHERE ELSE CAN I LEARN ABOUT SWIZ?
48
Continued Learning
• http://swizframework.org– Starting point for everything– Wiki – everything in this preso is on the wiki
• Quickstart• Configuration• FAQ• Everything else
– @swizframework– Google Group –
groups.google.com/group/swiz-framework