The Space For App Developers

Beyond Plain Old HTML Objects

Swiz 1.0 Command pattern API explained

with 9 comments

As you may know the Swiz team has released RC2 of the upcoming 1.0 version. Among many improvements and bugfixes there is one new feature that brings a built-in command pattern to Swiz. As part of my prep work for Adobe MAX where I will be speaking about AS3/Flex Frameworks I wanted to investigate it in more depth. As you can read in the Swiz docs, this implementation borrows heavily from the RobotLegs framework, which I will be also covering together with Parsley. This approach is really clean and simple but to be honest I kinda hope that it will evolve in future releases to be more metadata-driven, which is actually what Swiz is all about ;)

In the example below you can see it in action (right-click to view the full source code).


This movie requires Flash Player 10

So how do we get started?

If, when you read this post, Swiz is still in RC2, then you will need to grab the latest source code from github and build it yourself, the released RC2 has some quirks in regards to its command pattern implementation.

The first thing you do is create a SaveUserCommand class that implements the IEventAwareCommand interface and has one execute function. Obviously this is the function that will implement the command logic. It doesn’t accept any parameters, so if you need any you should provide them by injection. UPDATE 23.09.2010: Triggering event is available through event setter function when you implement IEventAwareCommand instead of ICommand.

package com.riaspace.max.swiz.commands
{
	import com.riaspace.max.swiz.events.UserEvent;
 
	import flash.events.Event;
 
	import mx.controls.Alert;
 
	import org.swizframework.utils.commands.IEventAwareCommand;
 
	public class SaveUserCommand implements IEventAwareCommand
	{
 
		private var _event:UserEvent;
 
		public function set event(value:Event):void
		{
			_event = value as UserEvent;
		}
 
		public function execute():void
		{
			Alert.show("SaveUserCommand executed, userName: " + _event.userName);
		}
	}
}

Next you can map/configure our command using a MyCommands class that extends the Swiz specific CommandMap. Just a hint here for the Swiz team that it would be cool to have the ability to configure commands directly in BeanProvider in future releases ;)

package com.riaspace.swiz.configs
{
	import com.riaspace.swiz.commands.SaveUserCommand;
	import com.riaspace.swiz.events.UserEvent;
 
	import org.swizframework.utils.commands.CommandMap;
 
	public class MyCommands extends CommandMap
	{
		override protected function mapCommands():void
		{
			// Mapping UserEvent.SAVE to SaveUserCommand class
			mapCommand(UserEvent.SAVE, SaveUserCommand, UserEvent, false);
		}
	}
}

Now you can instantiate the MyCommands class in the BeanProvider like any other bean:

<?xml version="1.0" encoding="utf-8"?>
<swiz:BeanProvider
	xmlns:fx="http://ns.adobe.com/mxml/2009"
	xmlns:swiz="http://swiz.swizframework.org" xmlns:commands="org.swizframework.utils.commands.*" xmlns:configs="com.riaspace.swiz.configs.*">
	<fx:Script>
		<![CDATA[
			import com.riaspace.swiz.models.presentation.MainPM;
		]]>
	</fx:Script>
 
	<fx:Declarations>
 
		<configs:MyCommands />
 
		<swiz:Prototype type="{MainPM}" />
 
	</fx:Declarations>
 
</swiz:BeanProvider>

At last you can dispatch the UserEvent.SAVE event in your PM class and the SaveUserCommand.execute will be called.

package com.riaspace.swiz.models.presentation
{
	import com.riaspace.swiz.events.UserEvent;
 
	import flash.events.IEventDispatcher;
 
	public class MainPM
	{
		[Dispatcher]
		public var dispatcher:IEventDispatcher;
 
		public function btnExecuteCommand_clickHandler():void
		{
			dispatcher.dispatchEvent(new UserEvent(UserEvent.SAVE, "John"));
		}
	}
}

Written by Piotr Walczyszyn

September 20th, 2010 at 6:41 pm

9 Responses to 'Swiz 1.0 Command pattern API explained'

Subscribe to comments with RSS or TrackBack to 'Swiz 1.0 Command pattern API explained'.

  1. This is really great. I’ve been using Swiz since 0.64 and I must admit I always cringed at how large my controllers were getting. Organizing much of that logic into commands seems a lot cleaner, even if it resembles Cairngorm a little too closely.

    Still I wonder what the advantage of using a CommandMap is over just adding a [Mediate] tag over the execute methods. Is it to save the cost of instantiation (of each command)? Must be…

    Erich Cervantez

    20 Sep 10 at 7:27 pm

  2. Hi there!
    One thing i’ve never understand and i keep not to understand is why all these frameworks! Swiz is going to be like Robotlegs (im a robotlegs user indeed!!) ?!?! Why not one or two?! How many of them are out there 5 or maybe 10?!?! Why not to concentrate “our” (i say our improperly!) efforts on one?!?!?!
    cheers (from italy)

    jadd

    20 Sep 10 at 8:38 pm

  3. Hey Piotr, great post!
    What kind of metadata driven approach could you imagine?

    Sönke Rohde

    21 Sep 10 at 4:22 am

  4. Hi Sonke,
    I was thinking more of a mixed approach borrowed rather from Parsley, like
    here and here.
    First of all Swiz could have along swiz:Prototype another config type swiz:Command that could do the mapping without the need of extending CommandMap. Mapped class could have an execute function by convention or any other function annotated with [Execute] metadata tag. This would drop the need of referencing Swiz interfaces or classes.

    Another thing that is cool in Parsley is that you can have async commands and the result, error or status can be configured with metadata [CommandResult], [CommandFault], [CommandStatus] and appropriate selector.

    The last thing that I think would make Swiz implementation even easier to use is ability to pass event object to execute function. I think in most cases command function may require access to the properties of an event or event itself that it was triggered by. Like in my example if needed access to user object I would have to inject it through some global model most likely.
    Just my 2 cents,
    Piotr

    Piotr Walczyszyn

    21 Sep 10 at 8:37 am

  5. @Erich actually kinda Command pattern could be achieved with [Mediate] metadata tag, the only difference is that for [Mediate] the annotated class instance has to live in Swiz context.

    Piotr Walczyszyn

    21 Sep 10 at 8:47 am

  6. @jadd I believe that competition is really good, it drives innovation and gives the users freedom of choice. Each of these frameworks have some really cool and unique features. Having just one option always causes stagnation at some point.

    Piotr Walczyszyn

    21 Sep 10 at 10:35 am

  7. [...] Swiz 1.0 Command pattern API explained MVC (Model View Controller) alapú Flash keretrendszerből egyre több van manapság, ez a leírás Swiz 1.0-ban mutatja be a parancs tervezési minta(Command pattern) megvalósítását. [...]

  8. I have studded Cairngorm for over a year and I like the command pattern interface however Cairngorm is repetitively tedious and a waste of good time but it works. I noticed your command pattern example demonstrating Swiz 1.0 new commandPatern interface and it look neat and simple, but for some order why would you not put the MyCommands into the commands folder and for that sake just call it MapCommnds ? This should act as the central command processor for all user events and there for be dispatched to there perspective UserCommand, PLayMovieCommand, AddToCartCommand etc. This probably took you a few minuts to drum up and so it’s realy good Nice Job ;-) It would be nice to revisit this in the near future and expand more in-depth on this new API Interface the swis team have worked very hard to cater to Cairngorm users. One more though the new CommandPattern for swiz will help me migrate some small to medium enterprise projects in a very short time and I appreciate this allot.

    TJ

    29 Sep 10 at 9:20 pm

  9. Well to add my 2 cents I’m not concerned that Swiz borrows many things form Robotlegs. For me RobotLegs is the shinest, simplest IOC little framework I ever tried – loosely coupled one with many optional use (ex u can use different ioc or as3signals dispate of native evnents). It’s pureMVC based but add [Inject] metadata and is more decoupled to allow TDD. It’s something that was missed in Cairngorm from version 2.0. I don’t think it’s good for framework to be more metadata driven cause it will definitly gain it’s performance and overall clear of code, maby if the metadata will be loosely coupled and optional ;)
    thanks for posting

    michal

    29 Oct 10 at 4:44 pm

Leave a Reply