Robotlegs Book: ActionScript Developer’s Guide to Robotlegs
What a ride! Robotlegs has been an amazing project to work on for the last two years and we are excited to announce that the first book on Robotlegs is complete. This tome of knowledge was a collaboration between myself and Stray. She has written a great post that gives a lot of detail.
Print copies can be pre-ordered here. The e-version should be available soon and there will also be a bundle
An Introduction to Robotlegs AS3 Part 3: Services
This is the third part in the introductory series covering Robotlegs AS3 here on InsideRIA. In the first part in the series we learned what Robotlegs AS3 is and had a brief "HelloWorld" introduction to the Robotlegs Context and Mediator classes. In the second part we explored Models. This article is going to expand on those concepts and introduce Services.
If you missed the first two parts I recommend looking at them first:
What is a Service?
The name of this website is InsideRIA. A Service is your application's link to the I in RIA. Services provide your application an API to access web services, data sources, and other applications. This could be accessing the Twitter API, your company/client's web server, the file system, or a host of other sources of data outside of your application.
A Service makes remote calls and parses the results. After the results are parsed, the service will notify the rest of the application that data is ready and/or update a Model with the results. We want external data to live as short of a life as possible within our applications. As soon as we get the results, they are converted to a format that is specific to the application domain. This might be XML, JSON, or typed Objects from an AMF source. When we are working in a "controlled" environment, meaning the server-side mid-tier is within our control, sometimes we can avoid parsing altogether because the returned objects are already part of the application domain. In many situations we are accessing third-party servers and receiving "foreign" data. This is what we want to parse.
Let's make something!
So with the definition behind us, lets look at how a Service functions within a Robotlegs AS3 application. This example is going to make use of the basic Twitter Search API.
The diagram above is the general overview of how our service will function. It receives a request, asks the server for some data, parses the results, and notifies the rest of the application. The requests are generally made from Mediators and Commands. In this example, we are going to keep it simple and make requests to the service from a Mediator. In the next article we will talk about how Commands are a great place to access services. Let's take a look at the finished widget and then build it from the ground up.
An Introduction to Robotlegs AS3 Part 2: Models
This is the second part in the introductory series covering Robotlegs AS3 here on InsideRIA. In the first part in the series we learned what Robotlegs AS3 is and had a brief "HelloWorld" introduction to the Robotlegs Context and Mediator classes. This article is going to expand on those concepts and introduce Models.
If you missed it, here is Part One: Context and Mediators
What is a Model?
Model classes encapsulate your application's data and provide an API to access and manipulate that data. The other classes in your application will make requests of models via this API. When data on the model is updated, the model dispatches events that the other classes within your application can react to. Models are appropriate for capturing the domain logic, such as performing calculations or other manipulations. An example of this might be a shopping cart. When an item is added to the shopping cart model, the new total for all of the items in the cart will be calculated. The new total will then be stored on the model for access by other classes within the application. By placing this logic within your models, you ensure that it isn't scattered across the entire application and know exactly where to look to see how and when your data is being manipulated.
In addition to controlling access to data, models maintain the state of your application. State, in the sense of the data model, is not the same concept as a Flex State, which relates to controlling the appearance of your application. They are certainly related, but with a model, consider a list of objects. You want to keep track of which of these objects is selected, so the data model has a selected property which is updated with the currently selected item. Other areas of your application can now access this property to discover which item is selected and react accordingly.
Models can be written to be portable. Along with Services this is something to keep in mind when you develop your models. There are many common sets of data that can easily transport between one application and the next. Think of, as an example, a UserLoginModel or a ShoppingCartModel. Portability takes a bit more thought and energy, but no more than writing the same code over again for each project does.
The model deserves a lot of attention. It is the core of your application. The visual components get all the ooos and aaahs, but as a developer you know that data is the man behind the curtain. It is our jobs, as developers, to curate the data and deliver it to those beautiful interface items accurately. This is why isolating domain logic in the model is so important. By isolating it you have made it easier to locate, update, and maintain. With the basic definition of the model in hand, let's look at a small example application.
On to the code!
An Introduction to Robotlegs AS3 Part 1: Context and Mediators
We are presented with lots of choices these days when it comes to frameworks for Actionscript 3 development. This is a good sign. The open source community is alive and vibrant, and tools that make development easier are a good thing. Over the course of the last year Robotlegs AS3 has seen rapid growth in adoption. It is being leveraged by major media corporations, independent game developers, startups, and enterprises of all sizes.
This is the first in a series of Robotlegs articles that will appear here on InsideRIA. In the coming weeks, more articles in the series will detail core Robotlegs concepts and work through some more advanced concepts involving third party utilities and libraries built to interact with them.
This article uses Flex. Don't worry straight AS3 developers, the second part uses an example that is pure AS3.
What is Robotlegs?
Simply put, Robotlegs is a mechanism for wiring your objects together. ObjectA needs to talk to ObjectB. ObjectA doesn't want, or need, to know that ObjectB even exists. How can they communicate? The simple answer is through Events. With Flash, we have a native event system that is used to facilitate this sort of communication. Likely you use Events on a daily basis. Objects on the display list communicate via events, and event bubbling allows distant objects to receive messages from other display objects. What about objects that aren't on the display list? This is where a framework such as Robotlegs can really make life easier for you.
At its core, Robotlegs is a set of modular utilities and interfaces that provide tools to ease these communication tasks, reduce repetitive coding tasks, and manage dependency injection within your application. In addition to this core set of tools, Robotlegs provides a lightly prescriptive MVC+S (Model, View, Controller, and Service) implementation to get you started. If you have any experience with PureMVC you will quickly recognize the use of Mediators and Commands within the Robotlegs MVC+S implementation. If not, don't worry, we will be looking at these classes in more depth soon.
This article is going to give an overview of Robotlegs through a simple "Hello World" example. You will probably look at the example and say, "Eh? I could have done this in a single MXML file without all the hassle!" While probably true with a trivial example, keep in mind that on a large project this structure quickly becomes invaluable. That is the benefit of development with a framework in general. It allows us to effectively communicate concepts and understand a code base much quicker than a slapped together application with no patterns and practices.
This is not going an exhaustive dissection of Robotlegs, but hopefully it is enough to spark your interest. I've posted resources at the end of the article for further investigation. That said, let's look at some code!
Write high quality unit tested Actionscript 3 for fun and profit…
For the past year or so unit testing has been one of my favorite subjects. There are tons of books on the subject, but several really stand out. Here are my favorites so far:

Clean Code by Uncle Bob Martin
This book does cover unit testing a bit. It isn't the focus of the book, but regardless it sits here at the top of my unit testing list. Why? Because the hardest part of writing unit tests is writing code that can be tested in the first place. Get it. Read it. Learn it. Seriously. Uncle Bob rides in the vanguard in the battle against horrible dirty code.

The Art of Unit Testing by Roy Osherove
This is a small book, but it is stuffed to the gills with distilled information on the subject of unit testing. Don't be put off with the .NET examples. It doesn't make a difference at all. There are a couple of chapters that are .NET specific that you can just skip, but 90% of the book is killer information on testing your code.

Working Effectively With Legacy Code by Michael Feathers
Like Clean Code, this book isn't specifically focused on writing unit tests, but it totally is. Feathers defines "legacy code" as "code with no unit tests". You can quibble about the semantics of this definition, but you'd be missing the point of this kickass book. How do you take a pile of code with no tests and make it better in a safe incremental way? How do you stop producing legacy code at a furious pace? That's right, the code you wrote today is probably sitting in the "legacy" column already. Even if you are writing tight unit tested code you will likely stumble into code that isn't, and this book has tons of good advice on how to deal with it.

xUnit Test Patterns by Gerard Meszaros
This one is a monster. It is a duplex book with a strong narrative up front and a massive patterns catalog bringing up the rear. if you read a lot of unit testing books you will "feel" this one under the best ones as the giant upon whom they are standing. This is source material here, and might be my personal favorite. I think The Art of Unit Testing makes for an easier (quicker anyway) read and if you were to choose one or the other go for it. Don't choose one or the other though. Read both!

Growing Object Oriented Software Guided by Tests by Steve Freeman
While the above books touch on the concept of TDD it isn't their focus. This relatively small volume is a great introduction to the subject of test-driving your code. It steps out of simple unit tests and gets into the realm of integration and acceptance testing. It has a fabulous explanation of mocking and is a fantastic introduction to the "testing layer cake" that high quality maintainable applications are guarded with.
So what is the take away from all of these books? Unit testing is actually pretty easy. Writing clean testable code is harder. We (developers) tend to complicate unit tests a lot. We write them as integration, acceptance, or other more complex test types that are orders of magnitude harder to write and maintain. A unit should be tiny and easy to test. If it isn't, then something is probably wrong with the unit or the scope of the test. Unit tests are for developers by developers and shouldn't be considered an afterthought or some line item on a managers spreadsheet. A high percentage of test coverage should not be the goal. Quality over quantity. Confusing unmaintainable tests are a liability to a project. Concise readable unit tests can be a trusted asset.
As with all code, complexity is easy. It is the default. Elegant simplicity is much more difficult. At the end of the day, cramming all the information the above books offer into my head has me writing dead simple unit tests. It seems weird as I examine it, but that's how it has worked out. Study up and write some high quality tests. You will be well thanked by both your fellow developers and your future self.
Modular Robotlegs
WTF is a Modular?
Modular programming is a versatile technique for separating an application into smaller parts. Each module is effectively an application and can be developed independently from one another. In a typical modular application you will have a Shell that is loaded initially. The Shell will manage the loading of modules and displaying their contents. Flex modules can be visual components that extend the Module class, but this is certainly not the extent of what can be considered a module.

Robotlegs is well suited for modular application development. Each Context is encapsulated and provides its own internal method for communication. A barrier to writing modular applications thus far with Robotlegs is that while these Context objects can exist in abundance in an application, they aren't very useful from a modular standpoint unless they can communicate with one another. As with many things within the Robotlegs eco-system, this is best accomplished through the development of a utility that can be used in conjunction with the core framework to provide the specific functionality that we are looking for. There has been some good work done in this area, but with Robotlegs 1.1 and more specifically the 1.5 release of the default Dependency Injection provider SwiftSuspenders, we have been equipped with better tools to accomplish modular contexts in a Robotlegs application in a clean effective manner.
IntelliJ Idea Flex and Actionscript 3 Workflow: [Part 1] Creating a Flex Project
I've been using IntelliJ Idea 9 quite a bit in both production and personal work lately. It is a great IDE, with lots of useful features. This is going to be a series of short screencasts that highlight the workflow in Idea for Flex/Actionscript development. The first is a quick introduction and how to set up a Flex project. If you have any questions or requests for future videos in the series please feel free to leave them in the comments.
direct link to the video (42mb QT)
Resources
IntelliJ IDEA EAP Download Page
Jesse Freeman's IDEA Workflow series on InsideRIA
Robotlegs, AS3-Signals and the SignalCommandMap Example
Robotlegs and AS3-Signals play really well together. Both apply solid object-oriented principles to accomplish their respective goals. Signals is extremely well suited for automated Dependency Injection. By combining Signals and Robotlegs you are able to eliminate the use of Flash Events in the framework layer of your application. Eliminating Events means eliminating the ambiguity that can accompany Events and their String registry based approach to the Observer pattern. Signals provides a strongly-typed object-oriented approach to this same pattern.
With the standard Robotlegs MVCS implementation you leverage the events provided by Actionscript 3 to communicate amongst the various actors of an application. From models and services dispatching notifications of their actions to triggering commands, events are a core piece of the implementation. To facilitate the use of Signals within MVCS it was necessary to create an extension to allow for Signals to be registered as Command triggers. This need spawned the SignalCommandMap utility.
The SignalCommandMap extends the normal MVCS context and creates a SignalContext. The SignalContext instantiates and provides access to the SignalCommandMap alongside the other maps that are standard to Robotlegs. The SignalCommandMap allows you to map Signal classes and instances to commands that will be executed when the Signal dispatch() method is called. The value objects that are passed in the dispatch are then injected into the command alongside any other mapped injections you have created.
Let's take a look at a simple example that makes use of the SignalCommandMap and discuss some of the underlying code to see how it works:
Robotlegs Image Gallery Example using AS3-Signals and the Presentation Model
Jason Crist posted a thought provoking request for his upcoming presentation comparing Robotlegs and Swiz. He's got a clever knack for stirring the framework ant pile and getting developers eyes off their IDEs long enough to discuss their passions. In this case the developers include Ben Clinkinbeard, Shaun Smith, Jesse Warden and myself.
These conversations are always good natured. While we work on (or use) "competing" frameworks there is always a sense of mutual respect. We like our tools but have obvious inclinations towards the projects that we've invested our hearts and souls into.
Ben Clinkinbeard has pointed out (several times!) that Robotlegs is all about extending the MVCS classes. My stock answer is that there is a clear separation between the framework and the concrete MVCS implementation. To paraphrase Ben, "Well show it to me then!"
All of the "official" Robotlegs examples are making use of the MVCS implementation. Why? Because it is solid, recognizable, and fairly easy to get one's head around. It provides a common ground for developers and a set architectural structure which is a huge advantage in any team environment. It is important to make the distinction between the framework and the MVCS implementation. What does that even mean? At the core, Robotlegs is a modular set of tools to provide a convenient mechanism for wiring applications. Robotlegs is not doing class reflection. Robotlegs is not an automated dependency injection solution. Robotlegs is an adapter to a dependency injection solution,by default the lightweight SwiftSuspenders library. Through a set of tools, namely the MediatorMap, CommandMap, ViewMap, and the injection adapter Robotlegs provides a robust starting place to begin coding your application.
The MVCS implementation is a set of base classes loosely modeled on PureMVC. At the heart of the implementation is the Context. The Context creates instances of the various mapping classes, the injection adapter, and gives the developer a centralized IEventDispatcher that can be used for messaging between application tiers.. The other three classes, Actor, Mediator, and Command, reduce boiler plate and provide convenient access to injected dependencies typically used in the the MVCS tiers.
What if you hate PureMVC, don't want to extend any framework classes, or generally just want to work in a different way outside of a prescribed MVCS architecture?
No problem.
Here's the deal. Robotlegs, the framework, is a set of interfaces. You can effectively do whatever you want with these interfaces. You can make use of the base concrete implementations of the core interfaces, use a class from the MVCS implementation, implement your own concrete classes based on the framework core, bring in other libraries or any combination you can think of. In terms of a framework, Robotlegs can be whatever you want/need it to be.
Man Joel, that was a long intro. Where's the freaking code??!?
SlideshowPro Director via AMFPHP
I really like SlideshowPro Director. With version 1.0.9.9 and below, you could simply access it as an XML service. This was great. Very fast. Past that they reworked the application and introduced an API. This is probably a good move for many, but the API is geared towards PHP websites that want to utilize SSP Director for html/js/css purposes. What I need to do is access the resources through Actionscript 3. My first thought was use AMFPHP and simple access the API through PHP that way, but when accessing the API that way, it was dreadfully slow. It would pause while loading for a good 10 seconds sometimes. The overhead of the PHP backend and the API just don't cut it for use as an Actionscript service.
The solution was to simply skip the middle man and go at the database directly. Now it is lightening fast using this AMFPHP service endpoint:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <?php class GalleryService { function GalleryService() { $this->methodTable = array ( "getAlbumById" => array ( "access" => "remote", "description" => "Pings back a message" ) ); } function getAlbumById($albumNumber) { $dbhost = 'YOUR_MYSQL_HOST'; $dbuser = 'YOUR_USER_NAME'; $dbpass = 'YOUR_PASSWORD'; $dbname = 'YOUR_SSP_DATABASE_NAME'; $result_array = array(); $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'slideshow'; mysql_select_db($dbname); //be sure to guard against injection by casting the album id to int (thanks Shaun!) $query = "SELECT * FROM ssp_images WHERE aid=" . (int) $albumNumber; $result = mysql_query($query); while($row = mysql_fetch_array($result)){ $result_array[] = 'YOUR_PATH_TO_SSP_ROOT/albums/album-' . $row['aid'] . '/lg/' . $row['src']; } mysql_close(); return $result_array; //an array of url strings } } ?> |
There are all sorts of options you could do for this. You could set up value objects and send those back to Flash. All I needed for my purposes was the array of url strings. Simple, fast, and effective. Now we can manage our galleries with Director, and are free from the constraints of the official SlideshowPro for presentation.
What I really want is an official AMF service through Director. They are using CakePHP, and there are AMF solutions for that. Hopefully that would supply a fast, officially sanctioned AMF solution. Until than, the above works just fine.



















