Archive

Posts Tagged ‘Cairngorm’

Cairngorm: Getting Started – Part 4

This is fourth and conclusive part of “Getting Started” series of Cairngorm. I hope the first three parts must have shown you a door to enter to this framework. This article will brief about other parts of the Cairngorm and will leave for you to explore and getting into deep of this framework.

Lets start with the left out part of MVC, that is Model. Cairngorm encourages use of having a ModelLocator in the system (a Singleton one) though if you look at ModelLocator its not being referenced in the any other class in Cairngorm framework. So actually you have a choice here to have one or not, to have it singleton or have different model instances directly. Anyways, by definition and implementation the ModelLocator you create should implement IModelLocator interface (which is empty) and scope of this class will be having other model classes and client state maintainence. Each model or data can be then fetched by this ModelLocator.

public class SomeModelLocator implements IModelLocator
{
     ...
     public function get  mySomeViewModel():SomeViewModel
     {
          return _objSomeViewModel;
     }

}

Now lets move to the business layer which consists of delegates and services in Cairngorm. Command with help of Delegates pushes the data to the model. In simpler terms its just another class which connects a command with a service.

public class SomeDelegate
{
...
...
               public function SomeDelegate( responder : IResponder )
               {
                       this.service = ServiceLocator.getInstance()
                                          .getRemoteObject( "someServiceId" );
                       this.responder = responder;
               }

               public function getData() : void
               {
                       var call : Object = service.getData();
                       call.addResponder( responder );
               }

               private var responder : IResponder;
               private var service : RemoteObject;
...
...
}

Key points:

  1. Command instantiates Delegate.
  2. Command implements IResponder.
  3. Command knows only about delegate and provides its reference (‘this’ as IResponder) to the Delegate.
  4. Delegate invokes a Service (through ServiceLocator) and adds the responder (the Command instance) to Service.

So Delegate essentially doesnt do much other than loosening the coupling. Command is only bothered about the result and not from where it is coming from. To sum up business delegates is a proxy services for Command.

Finally the ServiceLocator, its a singleton class that holds the services at one place. Any delegate can request for a service (HTTPService, WebService etc) through it.

<cairngorm:ServiceLocator
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:cairngorm="/2006/cairngorm">

<mx:RemoteObject
id="someServiceId"
destination="servicename"
showBusyCursor="true">
</mx:RemoteObject>

</cairngorm:ServiceLocator>

This is all for what you require for getting started. I hope the series was beneficial for you. If it was; please spread the word. Share and cheer!!!.

If you need more information on above post drop a comment. Your comments are valuable and helps in molding the article so do share in.

Categories: Flex Tags: , ,

Cairngorm: Getting Started – Part 3

To get full benefit from the post I will suggest you to go through the following posts first:

http://brupp.com/blog/2009/09/feed-reader-in-flex/

http://brupp.com/blog/2009/09/cairngorm-getting-started-part-1/

http://brupp.com/blog/2009/09/cairngorm-getting-started-part-2/

Since Flex framework is event driven; Cairngorm is designed in keeping it in mind. For an event to dispatch you need three things:

1) Event – In case of Cairngorm it is “CairngormEvent”.

2) Event dispatcher – “CairngormEventDispatcher”

3) Listener – Handled by FrontController and Command

This is how an event is dispatched in Cairngorm framework:

CairngormEventDispatcher.getInstance()
                    .dispatchEvent(new CairngormEvent("POPULATEGRID"));

CairngormEventDispatcher is a singleton class used to invoke event using “dispatchEvent” function. “POPULATEGRID”  is a event identifier constant which the listener will listen to. Now where is the listener? Listener is the command (loosely said). Lets understand the Command first.

Command is a ephemeral class. It has a very short life. It is “executed” when an event is invoked and dies when the task is completed. Every Cairngorm event we create has an associated command class which handles the business logic when event take place. For a class to be a Command class it should implement the Cairngorm’s  ICommand interface:

package com.brupp.command
{
	import com.adobe.cairngorm.commands.ICommand;
	public class PopulateGridCommand implements ICommand
	{
         ...
              public function execute(event:CairngormEvent):void
	     {
              }

        }
}

The interface asks for the “execute” method which is so to say the listener function of the command class which gets called by FrontController.

OK! So now there is an event there is a listener (so to say) then how it is registered to listen who does the mapping of event and command. Here comes in the FrontController.

package com.brupp.controller
{
	import com.adobe.cairngorm.control.FrontController;
	import com.brupp.command.PopulateGridCommand;

	public class FeedreaderController extends FrontController
	{
		public function FeedreaderController()
		{
			super();
			addCommands();
		}

		private function addCommands():void
		{

			this.addCommand("POPULATEGRID", PopulateGridCommand);
		}

	}
}

So our FrontController is FeedreaderController which holds the mapping (check the code in bold) by utilizing “addCommand” method of “FrontController”. The “execute” method is the single entry to the Command class which is called by the Front Controller when a user-gesture indicates that the user wishes to perform a task for which a particular concrete command class has been provided. FrontController is a centralized request handling class in Cairnorm. As mentioned in Cairngorm API documentation, the role of the Front Controller is to first register all the different events that it is capable of handling against worker classes, called command classes. On hearing an application event, the Front Controller will look up its table of registered events, find the appropriate command for handling of the event, before dispatching control to the command by calling its execute() method.

Diagram below demonstrates the role and flow of control in Cairngorm. Other than what we have discussed in this and previous post the following also depicts the Model. Only Command can change the model. View elements can be bound by model properties so that when a property is updated the View doesnt has to listen and fetch for this information. It is handled all internally by Flex framework. Moreover Command can also update the View directly if the change in View isn’t dependent on Model property.

Cairngorm Micro Architecture

Cairngorm Micro Architecture

So by now you know know where to put which code in Cairngorm. Just to brief all the term/classes we read:

ViewHelper - Your view helper should have code to interact/change view. Remember the class in no brainier. It can just update the view and has no business logic.
FrontController - The front controller shouldn’t do more than mapping events with commands.
Command - Put the brain here. Command can update Model and View (through view helper). Uses delegates to fetch data. Will discuss more on these in the next article.

Categories: Flex Tags: , ,

Cairngorm: Getting Started – Part 2

We will pickup from where we left in the last article http://brupp.com/blog/2009/09/cairngorm-getting-started-part-1/. So lets redesign the feedreader application built in one of the previous post (http://brupp.com/blog/2009/09/feed-reader-in-flex/). Before continuing I ll suggest you to go through the previous two posts I have mentioned or else you will feel off track. At the end of the post you will have fairly good understanding on ViewHelper.

Create a new MXML application file which will be the “default” application file in our case. For the sake of understanding we will name it “FeedreaderUsingCairngorn.mxml“. This mxml is the main view of the application for which we will have a viewHelper, where all the view interaction code will be written.  Lets call it “FeedreaderViewHelper.as”

Download the complete example from here.

package com.brupp.view
{
  public class FeedreaderViewHelper extends ViewHelper
  {
	public function FeedreaderViewHelper()
       {
	       super();
	}
  }
}

Note the helper class should extend the Cairngorm’s ViewHelper. Next is how to provide the “view” access to this helper class. It’s dead simple, just instantiate the helper object in the “FeedreaderUsingCairngorn.mxml” file.

<view:FeedreaderViewHelper id="viewHelper"  />

Now the catch is the “id” that you give to the helper that actually serves as an identification to locate the helper from any class through the Singleton class “ViewLocator” (part of Cairngorm architecture). What happens is that the helper thus instantiated registers its identity mapped with its “id”, while doing so the “ViewHelper.as” class (Cairngorm framework class which is the parent class of our FeedreaderViewHelper) also stores the instance of “FeedreaderUsingCairngorn” in a property named “view” from where it was created. This is an internal mechanism (Will discuss in Advance Cairngorm tutorial series). So now our helper class can access the main view through “view” property like this:

package com.brupp.view
{
  public class FeedreaderViewHelper extends ViewHelper
  {
	public function FeedreaderViewHelper()
       {
	       super();
	}
...
        public function onItemClick(e:ListEvent):void
	{
               FeedreaderUsingCairngorm(this.view).....
	} 

...
  }
}

Now once you have access to the view all the public objects can be accessed by helper; this way you dis-tangle the code from design. A viewhelper can serve multiple related views. Say if the main view has a sub-view called “FeedreaderView.mxml” then this view can have its method defined in the “FeedreaderViewHelper.as” itself. So we will put all our design elements that we created in our “Feedreader” post earlier here with only change that its events are now handled in FeedreaderViewHelper.

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" >
<mx:Script>
<![CDATA[
import com.brupp.view.FeedreaderViewHelper;
import com.adobe.cairngorm.view.ViewLocator;

[Bindable]
private var _objViewHelper:FeedreaderViewHelper;

public function onCreationComplete():void
{
_objViewHelper = ViewLocator.getInstance().getViewHelper("viewHelper") as FeedreaderViewHelper;

}
]]>
</mx:Script>
...

<mx:DataGrid id="dgFeed" width="100%" height="100%"
itemClick="{_objViewHelper.onItemClick(event)}"
doubleClickEnabled="true"
itemDoubleClick="{_objViewHelper.onItemDoubleClick(event)}">

...
</mx:VBox>

Two important things (in bold) to note. Notice in the code above how the helper is accessed and how the event handling is passed to helper. So just to get started with Cairngorm you need a view and a viewHelper and voila you started digging into the framework slowly.

Summarizing ViewHelper (taken from Cairngorm API documentation) :
ViewHelper is used to isolate command classes from the implementation details of a view. Model-View-Controller (MVC) best practices specify that command classes should interact with the view using the model (see the ModelLocator class), but, in some instances, command classes may require to both interrogate and update the view directly. Prior to performing any business logic, the command class may require to fetch values that have been set on the view; following completion of any business logic, the final task may be for a command class to update the View (user interface) with any results returned, or perhaps to switch the View entirely (to a different screen).

By encapsulating all the logic necessary for interrogating and updating a particular View into a single helper class, we remove the need for the command classes to have any knowledge about the implementation of the View. The ViewHelper class decouples our presentation from the control of the application.

A ViewHelper belongs to a particular View in the application; when a ViewHelper is created, its id is used to register against a particular View component (such as a particular tab in a TabNavigator, or a particular screen in a ViewStack). The developer then uses the ViewLocator to locate the particular ViewHelper for interrogation or update of a particular View.

I’m sure a lot of above must have started making sense to you now except the “Command” stuff. Right? Keep hooked to my future posts. So going back to the feedreader example we now need an event to call the web-service to populate our grid. CairngormEvent, Command and FrontController conjunction serves the purpose and we will see how in the next post.

If you liked this post, please spread the word. Share and cheer!!!.

If you need more information on above post drop a comment. Your comments are valuable and helps in molding the article so do share in.

Categories: Flex Tags: , ,

Cairngorm: Getting Started – Part 1

This is the first one of the series of article about Cairngorm Framework. This is for a beginner who is lost in bunch of classes the Cairngorm comes with. Prerequisite is that you have hand-on experience in Flex and have an idea of design patterns, atleast MVC (if you don’t have please leave a comment and based on requests received I may cover it next series). I am sure you had gone through various other resources, tutorials about Cairngorm before you reached here. Your search will end here. I will try to put it in a lay man’s language and would leave aside the tech jargon. I might not cover all the aspects/features of Cairngorm but surely at the end of this series you will be able to play around Cairngorm classes.

Cairngorm is an architectural framework which was designed to meet the need to medium to complex RIA applications. It is a skeleton which can be used as a starting point for creating your application’s architecture (for more about this, read http://www.adobe.com/devnet/flex/articles/cairngorm_pt1_02.html).  For the sake of understanding, in this article we will look at re-creating the feed reader application which I created in my previous post. Please go through the post as I would be referencing the same in this post. Click here to Download Cairngorm 2.2 .

Before continuing any further lets visit definition of some commonly related (yet different) terms. “Architecture” should be looked specific to the application’s need. So if you have to design a complex application you build an architecture to wrap your application around it. “Architectural framework” (Caringorm, pureMVC, Swiz, Mate etc) can be used as a base for your application architecture. “Application framework” like Flex can be used as a solution for you application design.

There are two ways to study Cairngorm, one is to understand different parts/elements of it and see how and why they are there. Other is to see how and why it actually evolve. I will follow the latter and will start it by taking one of the design pattern it uses and will put each element one by one “in and circum-scribing” it. Cairngorm design aids in separating user gesture, business logic and state of application. It favors event driven programming model. MVC being the principle design pattern on which the Cairngorm is based we will start taking a basic MVC as a starting point and see how different design pattern plugs in and give shape to Cairngorm. Figure below shows the basic communication channels in MVC.

mvcWhen user interacts with the view elements the interaction is directed to Controller. Controller, based on the interaction could either directly respond back to View to update itself (if no change in model) or can ask the model to update itself. Model after doing so will give the update information to all the registered Views. View will fetch the updated data from Model and change itself.

This is just a broad level aspect of MVC there are other communication that can happen in a MVC;  even independent of user interaction, for example Model updating itself after some time interval (stock prices, clock etc). MVC  in itself utilizes different design patterns like Observer and Strategy.

View is essentially where the visual elements are kept so its better to separate the View’s code from the View itself. What this means is that the view’s code/functionality, lets say it ViewHelper, will have all the functionality code to change/update the view (keep in mind that this helper won’t hold the business logic). ViewHelper is a layer of separating the View from other environmental elements. This is an interesting concept of Cairngorm, however it is deprecated in its current release, but I still favors it.

In this article you get to know about frameworks and the first element (ViewHelper) of Cairngorm. In the next article we will look into Commands, Controller.

If you liked this post, please spread the word. Share and cheer!!!.

If you need more information on above post drop a comment. Your comments are valuable and helps in molding the article so do share in.

UPDATED: Next post will elaborate a bit more on ViewHelper

Categories: Flex Tags: , , ,

Creating Feed reader with Flex

This is small article which will detail out steps for creating a feed reader in flex. I know there are lot of feed readers in this world and I am not intended to leave a mark in that space. This article is actually a precursor to my next article which will be about “Cairngorm” framework in which I will take this as an example and base it on Cairngorm framework. So you will be able to compare which lies where in framework and why? If you want me to notify you when the next article is released either subscribe to the feed or leave your comment.

Before you read further, please download the source from here .

The essentials for creating the feed reader as you can see in code are:
a)  HTTPService object (non visual) – To make an HTTP request to the feed url. Note that the resultFormat is set to “e4x” and the result of this request will call “onResult(event)” method.

b) DataGrid - The result will get populated in this. Note that the dataProvider is bound to the _xlFeed in which the result will be populated.

c) TextArea - To show the content of the feed article when DataGrid row is selected.

Feedreader_img

The flow:

1) On creationComplete the HTTPService is invoked with send().
2) On receiving the result the _xlFeed value is set to the list of”item” nodes of the feed xml.
3) As a result the DataGrid shows the result in coloumns as title and published date (you can add more columns, DataGridColumn in the DataGrid)
4) Clicking on an item in DataGrid, extracts the “description” from that item (onItemClick method)
5) On double clicking the item, another node “link” is accessed from the feed and new webpage is launched (onItemDoubleClick method)

Play with other node values and get creative. Extend the application e.g. add feed urls at runtime etc. “Debug” run the application with breakpoint to observe feed structure. Most importantly you should have “namespace“s defined for rss and atom (depend on feed type)  other wise the application won’t work. If this article did any help to you then please spread the word and share this.

Categories: Flex Tags: , , ,