Desktop

May 23rd, 2012

Using Cairngorm with Adobe Flex – Part1

More articles by »
Written by: Nouman Naveed
Tags:
Cairngorm Components for Flex Application in Flexatom.com

Introducing Cairngorm

Cairngorm Framework was created by Alistair McLeod and Steven Webster (currently with Adobe consulting team) in 2005 and later open sourced in 2008. Cairngorm is best suitable for mid-large applications where all responsibilities of MVC layers can be divided effectively. It is specifically designed to facilitate complex state and data synchronization between the client and the server, while keeping the programming of the View layer detached from the data implementation. I would recommend anyone this framework for making application code more organized. Cairngorm is still evolving with new capabilities. If you are looking for serious Cairngorm development then I suggest you to pick some good book with deep explanations. My article is for people who are new to Cairngorm framework and this article is written for Flex 3.6 version but you can change your code to work with Flex 4 / 4.5 version.

Cairngorm is not only MVC framework available in market today, we have PureMVC, Mate Framework and few others. PureMVC is also recommended framework for Flex Applications as it has few more advantages over Cairngorm framework. However, my main focus here will be with Cairngorm framework. Before we start with coding we need to focus on few important concepts.

  • Understanding purposes
  • Review the benefits of using Cairngorm
  • Learn about the components of Cairngorm

Understanding the purpose of Cairngorm

  • Cairngorm is an approach to organizing and partitioning
    • code and packages (all your Value Objects, business logic and custom events, views etc)
    • component functionality and roles
      Cairngorm Layers for Adobe Flex Application
  • Cairngorm is a “best-practice” methodology for Flex software design and development
  • Cairngorm encourages developers to identify, organize, and separate code based on its roles/responsibilities.
  • Cairngorm encourages separation of concerns
    • Model holds data objects and the state of the data
    • Controller process business logic
    • Views render data and announce gestures with events
    • Views communicate with Controller using events
    • Views watch Model with data bindings
      • Views are graphical user interfaces or visual portions of the
        Flex application.
      • Views usually are composites of UI controls or other views.
      • Views can contain child views
      • Even <mx:Application /> is a view
Fstop application for Adobe Flex Cairngorm


Reviewing the benefits of using Cairngorm in Flex Applications

  • Cairngorm allows designers, component developers, and data-services
    developers to work in parallel
  • Cairngorm is best suited for medium to large-size applications
  • Cairngorm is ideal for team development
  • Cairngorm provides the following benefits
    • maintenance is easier
    • debugging is easier
    • feature additions and/or changes are easier
    • automated testing of business logic and data access is easier
    • using mock data-services is easier

Learning about the components of Cairngorm

  • Cairngorm has 5 primary components that are used with Flex RIA solutions
    • ModelLocator: a repository for global data and global access
    • Services: a respository of pre-configured RDS components
    • Commands: non-UI components that process business logic
    • Events: custom events that trigger the business objects
    • [Commands] to start processing
    • Controller: component needed to route business events to commands for processing.

Using Cairngorm in Flex RIAs

  • Identify Roles of Code
  • Refactor Code to Cairngorm MVC Layers
  • Review Benefits of Cairngorm Refactoring

Identifying roles of code

  • Within the source code for a Flex application identify code that has a role- or is responsible for data, GUI, business, or data services.
    Identifying roles of existing flex application
  • Using the example illustration [from the FStop application] above, let’s identify specific code “roles”:
    • Inside <mx:Script />
      • [Bindable] public var declarations are part of “Data” roles
      • The remaining is for either business or data access.
    • After <mx:Script />
      • These are controls and components instantiated using MXML tag notation.
      • <mx:HTTPService /> is a non-UI controls in the “Data Access” role
      • All other <mx: /> tags are view components associated with the “GUI” role
      • <v: /> tags are custom view components with “GUI” roles

Refactoring code to Cairngorm layers and classes

We will first begin with non-Cairngorm application and understand how to integrate all Cairngorm components for making fully functional Flex application. There could be some concepts very confusing and want you to keep focus on each component in detail.

Refactoring code to use Cairngorm can be achieved by:

  1. Isolate the “ui” tags in the FStop application file in the View layer
  2. Move the “data” code to the ModelLocator in the Model layer
  3. Create custom [business] events to communicate from the View layer to the Controller [business] layer.
    1. AddPhotosToCartEvent
    2. LoadPhotosEvent
  4. Move the “business” code to the Controller layer
    1. Business logic is moved to the LoadPhotosCommand
    2. Business logic is moved to the AddPhotoToCartCommand
    3. RDS data access is moved to the Services repository
  5. Create FSController component to route business events to PhotoCommand
  6. Update View components to databind to ModelLocator data
  7. Update View components to dispatch business events.
  8. Update Application to create the FSController, Services respository, and ModelLocator instances.
Identifying New Classes Required for Cairngorm Refactoring in Flex Application

Reviewing benefits of Cairngorm refactoring

  • View code is concise and understandable and “renders” only.
  • View classes do not know anything about Controller [Business] components; except through the use of business events
  • Model data is stored and accessed from the ModelLocator.
  • All ModelLocator variables support data binding.
  • Business components do not know anything about the View classes.
  • View components use data binding to render data cached in the ModelLocator [Model] lay

Benefits Code Simplicity when using Cairngorm MVC for Flex

Practical 1 (Using Cairngorm in a Flex project)

Set up the working environment

  1. Unzip the file f3ic_studentFiles_16Jun08.zip to disk. It will automatically create an f3ic folder with supplied files in it. (Please download it from link available at the end of this article)
  2. Open Flex Builder.
  3. Select File > Import > Flex Project…
  4. Browse to {installationLocation}/f3ic and select the archive f3ic_fstop.zip.
  5. Click Finish.
  6. Click the project just opened, then select Project > Properties > Flex Build Path >Library Path.
  7. Select the Add SWC… button and add the Cairngorm library located at
    {installLocation}/f3ic/Cairngorm.swc.
Adding Cairngorm Framework to Flex project library

Implementing the ModelLocator

  • The ModelLocator is a global singleton repository for shared or global data
    • Singleton means that only instance of the class should exist
  • Does not load or persist data to a permanent data store
  • Does not contain business logic
  • Serves as caching and access location only
  • Caches custom variables/data specific to application
  • Supports data binding for auto-notifications of data changes to views

Example ModelLocator code

package model

{

import mx.collections.ArrayCollection;

[Bindable]

public class ModelLocator

{

static private var __instance:ModelLocator=null;

public var photoData:ArrayCollection=new ArrayCollection();

public var purchasedPhotos:ArrayCollection=new ArrayCollection();

static public function getInstance():ModelLocator

{

if(__instance == null)

{

__instance=new ModelLocator();

}

return __instance;

}

}

}

 

Using the ModelLocator

  • Access data stored in the ModelLocator via the getInstance()
    method
    <![CDATA[import model.ModelLocator;private var __model:ModelLocator=ModelLocator.getInstance();]]>
  • Access data via the instance name of the ModelLocator<mx:DataGrid dataProvider={__model.photoData}/>

Practical 2 (Building the Cairngorm ModelLocator)

  1. In the FB Navigator view, open the src directory.Create the ModelLocator Repository
  2. Create a new package called model.
  3. Create an ActionScript class called ModelLocator.as.
    1. Uncheck the “Generate Constructor from super class” checkbox.
  4. Create a static, private variable named __instance, data typed
    as ModelLocator, and set it equal to null.static private var __instance:ModelLocator=null;
  5. Create a global accessor function to allow only one ModelLocator instance to be accessed from anywhere. This function should be called getInstance().static public function getInstance():ModelLocator{if (__instance == null){

    __instance=new ModelLocator();

    }

    return __instance;

    }

  6. Open FStop.mxml application file.
  7. Copy the business variables declared for photoData and purchasedPhotos model data [see lines 17-18].
  8. Return to the ModelLocator.as class.
  9. At the top of the class paste the copied code into the ModelLocator.
  10. Modify the variables declarations to be public.
  11. Remove the [Bindable] tags on each variable.
  12. Make the ModelLocator class [Bindable] .
  13. Since you copied in the variable declarations, you need to import the ArrayCollection class.
  14. Be sure the ModelLocator appears as follows.package model{import mx.collections.ArrayCollection;[Bindable]

    public class ModelLocator

    {

    public var photoData:ArrayCollection=new ArrayCollection();

    public var purchasedPhotos:ArrayCollection=new ArrayCollection();

    static private var __instance:ModelLocator=null;

    static public function getInstance():ModelLocator

    {

    if(__instance == null)

    {

    __instance=new ModelLocator();

    }

    return __instance;

    }

    }

    }

  15. Save the file.
  16. Close the ModelLocator file.

Implementing the Cairngorm ServiceLocator

  • The ServiceLocator pattern is used to create a global, singleton registry
    to centralize all instances of Flex RDS components used in an application

    • HTTPService
    • WebService
    • RemoteObject
    • Custom RDS classes
  • Supports easy lookup of services by name
  • Should never be used outside the Control layer

Example ServiceLocator code

  • Extends the Cairngorm ServiceLocator class
  • Contains RDS tag instantiations<?xml version=”1.0″ encoding=”utf-8″?><rds:ServiceLocator xmlns:rds=”com.adobe.cairngorm.business.*”xmlns:mx=”http://www.adobe.com/2006/mxml”><mx:HTTPService id=”photosIn” url=”assets/photos.xml”/>

    </rds:ServiceLocator>

Using the ServiceLocator

  • Instantiate the object in MXML to configure and cache the services repository<rds:Services xmlns:rds=”business.*”/>
  • Use the ServiceLocator by calling the getInstance() method and then use a defined serviceprivate var __locator:ServiceLocator=ServiceLocator.getInstance();var service:HTTPService=__locator.getHTTPService(“photosIn”);

Practical 3 (Building the Cairngorm ServiceLocator)

  1. In the Navigator view, select the src directory.Create the Services respository
    Creating Cairngorm Service Repository in Flex Application
  2. Create a new package called business.
  3. In the business package, create an MXML Component named Services. This class will extend ServiceLocator.
  4. Modify the default namespace entered, xmlns=”*”, to properly import
    com.adobe.cairngorm.business.*. Use the rds prefix.<rds:ServiceLocator xmlns:rds=”com.adobe.cairngorm.business.*”xmlns:mx=”http://www.adobe.com/2006/mxml”></rds:ServiceLocator>
  5. Open FStop.mxml application file.
  6. Copy the tag declaration for the HTTPService
  7. Paste the tag into the Services.mxml class. Paste the code as a child tag.
  8. Remove the result event handler defined in the HTTPService tag.<mx:HTTPService id=”photosIn” url=”assets/photos.xml” />
  9. Check to be sure your ServiceLocator appears as follows.<?xml version=”1.0″ encoding=”utf-8″?><rds:ServiceLocator xmlns:rds=”com.adobe.cairngorm.business.*”xmlns:mx=”http://www.adobe.com/2006/mxml”><mx:HTTPService id=”photosIn” url=”assets/photos.xml”/>

    </rds:ServiceLocator>

  10. Save and close the file.

Cairngorm Flex Project Files


About the Author

Nouman Naveed
My name is Mohammed Nouman Naveed. I work and play with Flash Platform technologies and has experience of 11 years. Consulting and Training is part of my job. I am Adobe Certified Instructor, Adobe User Group Manager, Adobe Certified Expert and Adobe Community Champion.




 
 

 
CQ5
adobe aem56 dam logo

Setting Images in DAM

All images are loaded into the DAM (Digital Assets Management). To upload an image, you’ll need to use your Activator login. From the tree, click +Digital Assets Find the way to the tree to suitable folder (AAFP, images, ANN,...
by Nouman Naveed
0

 
 
 

Apache Flex 4.10.0 Available

Here comes Apache Flex 4.10. This project, the all-volunteer group of developers, and stakeholders in the development framework, today announced the release of Apache Flex 4.10.0. This release makes some important improvements ...
by Nouman Naveed
0

 
 
CQ5
aem 5.6.1 features pic

Many New Features in AEM 5.6.1

AEM 5.6.1 is a easy to use, unified experience management collection for marketers in the digital sphere to use in creating, managing, and delivering unique online experiences that are brand-entered and increase demand across d...
by Nouman Naveed
0

 

 
CQ5
Adobe CQ5 WEM, SOCO, Tagging, DAM

What’s New in CQ 5.6

1: It’s called AEM (Adobe Experience Manager) now Though I guess not that essential, it’s going to be exciting if the name is going to attach – there were other occasions where Adobe tried to rename this result and at the...
by Nouman Naveed
0

 
 
CQ5
content management for web and mobile

Content Management for Web & Mobile

Adobe CQ is a WCM and gives a better browser-based user interface. It is best suitable for business and IT for creating interactive, multimedia rich, multichannel consumer understanding to make an engaging digital existence, ma...
by Nouman Naveed
0

 




0 Comments


Be the first to comment!


Leave a Reply

Your email address will not be published. Required fields are marked *