Razvan Surdu Personal Blog

29Nov/090

One simple arhitecture for flex

Project Structure

Project Structure

I am writing this article because many have asked me how to start a flex application and what are some best practices when laying out the foundation. I will create a mini project for this purpose and I will underline some important principals that you should consider when starting a flex application.

Ground rule: Separate your code using the Model - View - Controller design pattern. You don't what to be faced with the situation when you have a lot of lines in a single mxml file and you must quickly fix a critical bug, or you look on someone else code and don't have a clue where to develop the new feature that the project manager wanted.

Starting with the Model, I create a action script class MovieLibModel. In this class I create all the business elements of the application. In my example here I create the public var movies which holds all the movies loaded from the database. The class is a singleton and I can access it's methods from anywhere in the application using the getInstance static method. If I had a more complex application here I would store the user state, his favorite movies or any kind of data that I will later need in the interface.

package model
{
	import mx.collections.ArrayCollection;

	[Bindable]
	public class MovieLibModel
	{
		static private var _instance:MovieLibModel = null;

		public function MovieLibModel()
		{
		}

		static public function getInstance():MovieLibModel
		{
			if (MovieLibModel._instance == null)
			{
				MovieLibModel._instance = new MovieLibModel();
			}

			return MovieLibModel._instance;
		}

		public var movies:ArrayCollection = null;
	}
}

The View is represented by the application interface. Panels, buttons, alert messages and other UI elements form the visual part of the program. This part is mostly created by designers in tools like Photoshop, Fireworks and the exported with Flash Catalist. In flex you create components for the login zone, for product display page etc and you bind the visual elements to the model data. In my example I create two panels one with a datagrid used to list the movies and one with a form for adding a new movie to the databse.

interface

Application Interface




	
		

	

	
		
			
				
					
					
					
				
			
		

		
			
				
					
				
				
					
				
				
					
					
				
				
					
				
			
		
	

Now we must bind the two elements together. When the user inserts a new movie it should be added to the database, and the movie datagrid updated. For this we use the Controller. It's main roles are to handle the actions dispatched by the view, update the model, exchange data with the database or other external services. In this example I use a simple http service to communicate with the backend which is a php script.

package controller
{
	import model.MovieLibModel;

	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	public class MovieLibController
	{
		static private var _instance:MovieLibController = null;

		public function MovieLibController()
		{
			init();
		}

		static public function getInstance():MovieLibController
		{
			if (MovieLibController._instance == null)
			{
				MovieLibController._instance = new MovieLibController();
			}

			return MovieLibController._instance;
		}

		public var appModel:MovieLibModel = MovieLibModel.getInstance();

		private var myService:HTTPService = null;

		public function init():void
		{
			myService = new HTTPService;
			myService.method = "POST";
			myService.url = "http://localhost/razvansurdu.com/movieLib/server/";
			myService.resultFormat = "array";

			myService.addEventListener(FaultEvent.FAULT, myService_faultHandler);
			myService.addEventListener(ResultEvent.RESULT, myService_resultHandler);
		}

		public function addMovie(title:String, rating:String, description:String):void
		{
			var o:Object = new Object();
			o.title = title;
			o.rating = rating;
			o.description = description;

			o.action = "addMovie";
			myService.send(o);
		}

		public function getMovies():void
		{
			var o:Object = new Object();
			o.action = "getMovies";

			myService.send(o);
		}

		protected function myService_resultHandler(event:ResultEvent):void
		{
			appModel.movies = event.result[0].data.movie;
		}

		protected function myService_faultHandler(event:FaultEvent):void
		{
			Alert.show(event.fault.faultString);
		}
	}
}

Based on this architecture you can add more features, add more visual elements and have a well organized app, easy to debug and maintain.

7Nov/090

Convert a Xml to an ArrayCollection in AS3

Here is a quick method to convert a xml to an array collection. Because you pass the XML url (Eg: './assets/data.xml') to the first argument you will receive the array asynchronous using the callback function. If you have already the xml content in a variable use only the code in the anonymous function at the event.COMPLETE dispatch.

static public function convertXmlToArrayCollection( xmlUrl:String, rootTag:String, repeatedElement:String, callback:Function ):void
{
	var xmlLoader:URLLoader = new URLLoader();
	xmlLoader.addEventListener(Event.COMPLETE, function(e:Event):void
	{
		var xml:XMLDocument = new XMLDocument( e.target.data );
		xml.ignoreWhite = true;

		var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
		var data:Object = decoder.decodeXML( xml );
		var array:Array= ArrayUtil.toArray(data[rootTag][repeatedElement]);

		callback(new ArrayCollection( array ));
	});
		xmlLoader.load(new URLRequest(xmlUrl));
}
20Aug/090

Creating a system tray icon and menu for your AIR application

private function createSysTray():void
{
	if(NativeApplication.supportsDockIcon)
	{
		NativeApplication.nativeApplication.icon.bitmaps = 	[ new icon16().bitmapData ];
	    var dockIcon:DockIcon = NativeApplication.nativeApplication.icon as DockIcon;
	    NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, showMainWindow);
	    dockIcon.menu = createIconMenu();
	} else if (NativeApplication.supportsSystemTrayIcon){
		NativeApplication.nativeApplication.icon.bitmaps = 	[ new icon16().bitmapData ];
	    var sysTrayIcon:SystemTrayIcon = NativeApplication.nativeApplication.icon as SystemTrayIcon;
	    sysTrayIcon.tooltip = "Tooltip";
	   	sysTrayIcon.addEventListener(MouseEvent.CLICK,function():void
	   	{
	   		//Icon Click Handler
	   	});
	    sysTrayIcon.menu = createIconMenu();
	}
}

private function createIconMenu():NativeMenu{
    if(NativeApplication.supportsSystemTrayIcon){
    	var iconMenu:NativeMenu = new NativeMenu();

    	var showSettingsCommand:NativeMenuItem = iconMenu.addItem(new NativeMenuItem("Edit Settings"));
    	showSettingsCommand.addEventListener(Event.SELECT, showSettingsWindow);

        var exitCommand: NativeMenuItem = iconMenu.addItem(new NativeMenuItem("Close"));
        exitCommand.addEventListener(Event.SELECT, function ():void
        {
        	stage.nativeWindow.close();
        });
    }
    return iconMenu;
}
Filed under: Examples, Flex No Comments
17Aug/090

From php to flex

Being myself a developer that started with php and moved to flex I encourage all of php developers to read this article: http://corlan.org/2009/08/14/flex-for-php-developers-article/. Mihai Corlan, one of the best flex evangelists, described in great details the similarities and differences between php and flex.

Here is the table of contents:

  1. What is Flex?
    1. Flex: two languages, one framework to bind them
    2. Why you should care about Flex
    3. From thin client to smart/rich client
  2. Introduction to the MXML language
    1. Mixing MXML with ActionScript 3
    2. CSS styles
    3. Modifying MXML code at runtime
  3. Introduction to the ActionScript 3 language
    1. Separating statements
    2. Data types, variables, constants
    3. Functions and Anonymous functions (closures)
    4. OOP: classes and interfaces
    5. Variable scope
    6. Arrays
    7. Namespaces
    8. Working with XML
    9. Dynamic ActionScript
  4. Flex is asynchronous
  5. Data binding, metadata tags, and reflection
  6. Where are my data, bring it on!
  7. User authentication in Flex and PHP projects
  8. Working on Flex and PHP projects
    1. Flex SDK
    2. Flex Builder / Flash Builder
    3. Debugging Flex applications
  9. What is Adobe AIR?
  10. What’s next?
  11. Where to go from here
Filed under: Flex No Comments
25Apr/091

Combining Flex, Zend Framework, Wordpress and … Iphone

I have been working on a new project who will combine all technologies written above. It is a movie tracking application that will let you track desired movies, and look for information on torrents site to inform you the availability of the movie, and it's quality (CAM, TS, DVD version etc).

The theme and the main scaffold of the website will be handled by wordpress, so I can manage posts, comments, pages very easily. The server side application will consist from php classes build on the Zend Framework and a Mysql database. On the frontend the main application will be build using Flex. Here you can browse movie, tag the one you like, mark them for "tracking" and other actions. Finally I will also build an iphone application that will keep you inform with what is new and all your movies status.

In a month I hope I will have a working beta of the system and then I will make public the url from where it can be accessed.

Tagged as: , , , 1 Comment
29Mar/090

Flickr Photo Gallery

Flickr Gallery

Flickr Gallery

Today I just finished working on a mini project called Flickr Photo Gallery. It is a flex application showing the latest public photos upladed on Flickr. It uses a php service that connects to Flickr API and exchange data. The backend service has also a caching system so after a image is viewed the next time that photo is requested it will be served from the local system not from the Flickr servers.

The flex application is build using Cairngorm architecture and all the source code is free to download and to modify. Click here to download.

Click here to open the application.

19Oct/080

Flex or Ajax RIAs?

The question that I want to ask today is whether a developer should build a rich internet application in Flex or in Ajax? There are a lot of differences and similarities between this frameworks and a lot of developers prefer to take a side toward one of them. If you had asked me this question a couple of months ago I would definably had chosen Flex, but after I studied the latest javascript frameworks and tools for building complex Internet application I realize that a lot had changed in the javascript world. Libraries like JQuery and template engines like Smarty are making the implementation phase of an Ajax app much more easier then in the past.

I found an interesting article describing both of this development models at adobe edge newsletter so if you are interested in starting a web app. this article would give you a quick preview of these frameworks.

Recently Adobe launched Flash Player 10 which includes a lot of new features and giving developers the tools to create revolutionary web experiences. The native 3D support of the new flash player is awesome and I will not be surprised seeing games like Quake, Doom ported to web. One major advantage of flash player is no more browser compliance testing! One thing about AJAX, it’s more complicated than plain ol’ XHTML and some CSS. Browser compatibility testing goes from a bad dream to a nightmare. Since Flex apps compile to Flash SWF files, they are identical down to the pixel, no matter which browser or operating system you’re using.

In the Ajax world tools are being created and upgraded to make code writing much more faster and better. The main advantage of Ajax is that it does not require a plugin installed on the browser. I know that flash player is running on 98% of the web, but sometimes you do not have the privileges required to install it, or you computer is very old and do not have the system performance necessary to render that swf.

From my point of view I think that both of them are very good and can help developers build great applications. You musk ask yourself how will the end-users, the clients would react in front of such application and by that take a decision. If the client wants some powerful UI elements choose definitely Flex, if your client wants his application to run without a plugin installed choose Ajax.

Tagged as: , No Comments
28Jul/080

Quick Flex MVC Framework

To understand what is Quick Flex MVC Framework (QFMF), I will start describing the common structure of a flex application, present some other flex frameworks, then explain why I created QFMF and why should a developer use it.

First of all a complex application based on flex framework has three main components: The Frontend Application, The Backend Server Script and The Database. The Frontend Application is the user interface which clients use and communicate with the backend services. In a flex powered application it consists in flex components with different states, effects and transitions, all combined into a swf. The client side browser can load this swf using the flash player and then the interaction between him and the application can trigger a backend script. The backend script can be php, java, asp, ColdFusion etc, but its main role is the same: to process the data received from the frontend application. Some of this data must be kept for future use so that’s why the third component comes into use: The Database. Its role is to store the information extracted from the user and provide it for future needs.

Some of the currently available flex mvc frameworks are Cairngorm, PureMVC, Mate etc. These frameworks focus only on the first component of the application: the Flex Frontend. They separate the actionscript code and have unique methods for transferring data between layers. Why they do that? A simple answer would be that a complex flex application can have a lot of code in it, thousand and thousand of lines. In an environment based on team work, it may be kind of impossible to work efficient together and know where you must edit changes or add new features. So the solution, based on the programming technique “divide et impera”, is to divide the code in layers, in components with precise role and scope. When a developer wants to modify the application he knows where he must make the changes and quickly resolves the problem. The main criticism I give to these framework is that they do not take in consideration the backend server script and the database layer.

Quick Flex MVC is a framework that focuses on all the application elements. It can generate actionscript files but also server side script and provide basic methods for database communication. In a couple of minutes it quickly generates an application scaffold, not only composed by as3 files but also php | coldfusion | J2EE etc server script and sql files for database initialization.

  • Every object is converted in a class with public properties
  • Create | List | Select MXML files – UI for basic actions
  • ObjectPeers.as and ObjectPeer.php* - Creates static methods for the basic database related actions ( Retrieve By Primary Key, Select, Update, Insert etc)
  • Application.sql* - every object is converted in a table with the object properties as columns

I attached a pdf presentation for the framework that you can download from here. Everything is still in development faze but I will post a tutorial and a movie to show you how to integreate this framework in the flex  workflow.