Getting Started with Cairngorm – Part 1

October 7th, 2007

I spoke about Cairngorm 2.2 in the Flex Bootcamp at Max this week. Many people were interested in Cairngorm, but I only had about 10 minutes to explain the basics of Cairngorm. I guess the easiest way to assist these people is to do a quick blog series on the benefits of Cairngorm. This series will combine articles with "code-along" videos.

Disclaimer: I do not claim the be "the expert" on Cairngorm - I am far from it. However, I have used Cairngorm on several large projects (both at Georgia Tech and in my own business). I am certainly open to corrections if you see that I have made an error on this project. If you want "the experts" check out: Steven Webster, Alistair McLeod, Alex Uhlmann, and Peter Martin.

Note: The guys at Adobe Consulting (that developed Cairngorm) are currently investigating some new things with the framework as a whole. It is possible (actually probable) that some of these things will change in the future. One of the very specific areas of change is the Model Locator.

Part 1 – Getting Started By Using a Model Locator

The Model Locator pattern is used in Cairngorm, but you don't have to have a full Cairngorm Implementation to use the pattern. First, let's cover what benefits that you get from using a Model Locator.

A Model Locator is a centralized repository for all of the data that is needed across your application. Your data will exist inside of a "singleton class". This "class" can only have one instance of itself. Why is this important? Let me give you an example.

We have great mini-notepads at work that I use to write down data while I work. However, sometimes, I lose a notepad – get a new one, and then find the old one. After both have been heavily used – it is really hard to find out which notepad I used to write down a piece of information from one week ago. That is a simple example – but imagine if I had 20 notepads? This could get crazy.

In the same way you could have a "class" that gets "instantiated" 20 times within your application (even if you don't mean for it to). The easiest way to eliminate this problem is to use a "singleton". A singleton is a class that is never "created" in the traditional way. It has one main rule – no more than one of itself can exist at any point in time. How does it do this? I will show you in the Model Locator example.

Actionscript:
  1. package net.davidtucker.CairngormSample.model {
  2.  
  3.     import com.adobe.cairngorm.model.IModelLocator;
  4.    
  5.     [Bindable]
  6.     public class ModelLocator implements IModelLocator {
  7.        
  8.         // Single Instance of Our ModelLocator
  9.         private static var instance:ModelLocator;
  10.  
  11.         public function ModelLocator(enforcer:SingletonEnforcer) {
  12.  
  13.         if (enforcer == null) {
  14.                 throw new Error( "You Can Only Have One ModelLocator" );
  15.             }
  16.         }
  17.         
  18.         // Returns the Single Instance
  19.         public static function getInstance() : ModelLocator {
  20.                
  21.             if (instance == null) {
  22.                 instance = new ModelLocator( new SingletonEnforcer );
  23.             }
  24.             return instance;
  25.         }
  26.        
  27.         //DEFINE YOUR VARIABLES HERE       
  28.        
  29.     }
  30. }
  31.  
  32. // Utility Class to Deny Access to Constructor
  33. class SingletonEnforcer {}

This code may look a bit daunting in the beginning, but trust me that it is not as difficult as it may appear. First, we have our package definition and we import some classes. Right now we know that we will need the IModelLocator interface. To use this you will need the Cairngorm SWC that can be found here: Cairngorm. Also note - you could build a model locator without Cairngorm, and I do this frequently on small projects (you just leave out the 'implements IModelLocator' and 'import com.adobe.cairngorm.model.IModelLocator' code from the Model Locator).

Actionscript:
  1. [Bindable]
  2. public class ModelLocator implements IModelLocator {
  3.        
  4.      // Single Instance of Our ModelLocator
  5.      private static var instance:ModelLocator;

Next we have our class definition. It is important that you use the Bindable metatag directly above your class definition. This will allow all of our variables that we define inside of the Model Locator to be used for binding. We also will go ahead and create one variable. It will be called "instance" and it will be of type ModelLocator. This will be the variable where we will store our one instance of our class. It will also be denoted as a "static" property. If you are not sure what a "static" property is, it's ok - we will discuss that in our next lesson.

Actionscript:
  1. public function ModelLocator(enforcer:SingletonEnforcer) {
  2.      if (enforcer == null) {
  3.           throw new Error( "You Can Only Have One ModelLocator" );
  4.      }
  5. }

This is followed by the constructor. The constructor takes on argument - "enforcer". You will notice that this "enforcer" has a type of "SingletonEnforcer" which is defined directly after our class. Here is the logic behind that:

  • When you put a class in an Actionscript file below the main class, it is only available to that class. Many people refer to these as "utility classes" (although many people use that term in a much broader scope).
  • If the constructor requires this argument - then only our main class can create an instance of itself, because we do not have access to the "SingletonEnforcer" class - only the main class has this access.
  • We will not access our class in the normal way by using the "new" statement because we can't call the constructor (I will show you how we will do it in a bit).

Once we get inside of the constructor, we have a few lines that make sure things work as planned. The "if" statement ensures that we had a valid "enforcer" passed in. If there wasn't it throws an Error stating that "You Can Have Only One ModelLocator".

Actionscript:
  1. // Returns the Single Instance
  2. public static function getInstance() : ModelLocator {
  3.      if (instance == null) {
  4.           instance = new ModelLocator( new SingletonEnforcer );
  5.      }
  6.      return instance;
  7. }

The "getInstance" function is how we will access our ModelLocator from our application. This function simply passes back the "instance" of the class. If it doesn't exist yet, it creates it. We can now get the ModelLocator by using the following code:

Actionscript:
  1. var model:ModelLocator = ModelLocator.getInstance();

Video Example - Getting Started and Building a Contact List

Application Code
Download (418 kB)

Cairngorm, Flex | Comments | Trackback | Del.icio.us | Digg | Technorati Jump to the top of this page

62 comments on “Getting Started with Cairngorm – Part 1”

  1. 01

    Great video tutorial, but what about the warnings I get?

    “Data binding will not be able to detect assignments to “modelLocator” “.

    Niels Bruin at October 7th, 2007 around 6:54 am
    Jump to the top of this page
  2. 02

    There must have been one item I left out:

    When you get the “instance” of your modelLocator - you need to make that variable Bindable as well. The binding will still work without it (since the entire Model Locator is bindable, but it will throw warnings unless you add the following code):

    [Bindable]
    private var modelLocator:SampleModelLocator = SampleModelLocator.getInstance();

    That should fix the warnings. Thanks.

    David Tucker at October 7th, 2007 around 6:57 am
    Jump to the top of this page
  3. 03

    Hehe, should have known that. When can we expect a new tutorial?

    Niels Bruin at October 7th, 2007 around 7:18 am
    Jump to the top of this page
  4. 04

    Neil Webb did a great series of posts on a introduction to Cairngorm

    http://nwebb.co.uk/blog/?cat=13

    My advice would be not to follow Cairngorm too strictly. Take the good things out of it for each particular project your working on.

    Tink at October 7th, 2007 around 8:17 am
    Jump to the top of this page
  5. 05

    The next tutorial should be out in a few days. It will be on “Binding the View to the Model Locator”.

    David Tucker at October 7th, 2007 around 11:14 am
    Jump to the top of this page
  6. 06

    hi folks.

    Great artical mate.

    Just wondering, does anyone know of an eclipse (or anything else in fact) tool for automatically creating VOs from MySQL tables?

    It’s just such a pain of a jop having to copy it all by hand, and also another place where errors can creep in.

    In fact it wouldn’t even need to creat propper actionScript code, just something like it that I could then change into the propper format.

    The project I’m currentl;y working on is a recoding of a system that was originally written in access and SQL. so the Database is already there (since converted in MySQL) and there are loads of tables and making all the VOs is becomming a real pain.

    any ideas anyone?

    cheers
    glenn.

    Glenn Williams at October 7th, 2007 around 9:23 pm
    Jump to the top of this page
  7. 07

    Yes, you can actually generate Actionscript VO’s with the Adobe Coldfusion Extensions for Eclipse - http://www.adobe.com/support/coldfusion/downloads.html . If you aren’t in a Coldfusion environment, this might be a pain.

    There is also a CRUD generator for Flex 2 Beta 3 that works with a variety of different languages. I am assuming that it creates VO’s on the client side as well as the server side code. More here: http://www.onflex.org/ted/2007/09/flex-3beta-2-crud-wizard-for-aspnet-php.php

    David Tucker at October 7th, 2007 around 10:26 pm
    Jump to the top of this page
  8. 08

    There’s also a great tool from Tyler Beck at http://www.tylerbeck.com/CairngormCreator/ for generating stub code for your project.

    Jason MacDonald at October 8th, 2007 around 12:02 am
    Jump to the top of this page
  9. 09

    I agree that is a good tool. I don’t believe that it has MySQL Introspection though. We will be covering that tool (as well as CairnGen) in a future tutorial.

    David Tucker at October 8th, 2007 around 12:11 am
    Jump to the top of this page
  10. 10

    Why does Anatole Tartakovsky take such exception to the Cairngorm framework?

    http://flexblog.faratasystems.com/?p=252

    “JB: Moving on other topic, I would like to talk on frameworks. Cairngorm and some other frameworks that I call “shallow” frameworks. They are not necessarily provide a lot of functionality in a sense that Flex frameworks does. It provides what you might call Superpad – a set of interlocking patterns. I wonder if a shallow framework provides cure or actually causes disease by blocking developers from providing solutions and analyzing the problems.
    AT: That is exactly the problem we are seeing. People come to us to rewrite Cairngorm projects. Cairngorm is answering to “how” question, but “why” or “what” just is not in the picture at that point. We believe that you should take some patterns – and enhance them on individual basis for a particular application, but the “meat” of the solution is in the developer’s framework. People need to have big pieces of an application available as components, customizable products that can perform common functions and transparently be used in the application. They are tested and give you the functionality that you want right away. You can start with small, single function components like logger or “caching logging” screen David mentioned, or you can try deep waters with complete set of components that very much fill the gaps in the current Flex frameworks. Over the years, we added objects like Report, DataForm, TreeGrid, OlapTreeGrid, etc. We added the functionality that is important for reliability of your applications like robustness layers for communications. Architectural frameworks are very much like skeleton of the application, and Application Framework is actually adds muscle – you can’t have one and not the other.”

    MarkyMark at October 9th, 2007 around 8:09 am
    Jump to the top of this page
  11. 11

    [...] In Part 1, I discussed the basic implementation and use of the ModelLocator pattern. This pattern is one of [...]

    Jump to the top of this page
  12. 12

    First code sample, line 22 you refer to “VizionModelLocator”. Is this a typo? I would have expected it to say this:

    instance = new ModelLocator( new SingletonEnforcer );

    Am I missing something? ( Quite possibly ).

    Great screecast, BTW. What did you use to create it? ( Camtasia? Captivate? Something else? )

    Jeffry Houser at October 29th, 2007 around 8:06 am
    Jump to the top of this page
  13. 13

    Jeffry - Yes this was an error (that is what I get for copying/pasting from another project I am currently working on). I have corrected it in the article, and I will correct it in the Application Code download as well.

    As for the screencast - I am using Camtasia. It is one of the few situations where I prefer another product over an Adobe product. I feel that overall, it does a better job than Captivate.

    David Tucker at October 29th, 2007 around 8:11 am
    Jump to the top of this page
  14. 14

    [...] Teil 1 beschreibt das ModelLocator Pattern [...]

    Jump to the top of this page
  15. 15

    [...] Part 1 [...]

    THE EYE OF RIA » Getting Started with Cairngorm at November 8th, 2007 around 1:57 am
    Jump to the top of this page
  16. 16

    Hello David,

    great video! I’m new with flex and cairngorm, and this video is very usefull
    i’m getting an error on this line:
    ——————–
    instance = new SampleModelLocator( new SingletonEnforcer );
    ——————–

    I’m getting the following error:
    ——————–
    Incorrect number of arguments. Expected 0.
    ——————–

    I don’t know what is wrong, do you know what could be wrong

    thanks!

    Laurens van der Plaat at November 9th, 2007 around 4:32 am
    Jump to the top of this page
  17. 17

    never mind,
    I’ve found it, i wrote something wrong a bit above that line…

    Laurens van der Plaat at November 9th, 2007 around 4:52 am
    Jump to the top of this page
  18. 18

    @Laurens - Great. Please let me know if you have any more problems.

    David Tucker at November 9th, 2007 around 4:53 am
    Jump to the top of this page
  19. 19

    Hi, it maybe a stupid question but .. Im follow the tutorial but how do you make eclipse code hint the AS scripts (SampleModelLocator.as) Mine doesnt .. :(

    Joel at November 20th, 2007 around 11:46 pm
    Jump to the top of this page
  20. 20

    David, this series is amazing!!! Helping me so much to really understand the framework and your explanations hit every single question I have had. Just one thing I noticed, your video uses SampleModelLocator as a naming convention, but your written tutorial uses ModelLocator. Keep up the great work and thanks again for the hard work!

    Conrad

    Conrad at December 3rd, 2007 around 9:30 am
    Jump to the top of this page
  21. 21

    [...] Part 1 [...]

    Jump to the top of this page
  22. Jump to the top of this page
  23. 23

    I do not understand the necessity of SingletonEnforcer. If the constructor is declared private it cannot be accessed from anywhere outside the class.

    T. Venkat Ram at December 25th, 2007 around 3:30 am
    Jump to the top of this page
  24. 24

    @T. Venkat Ram - Actionscript 3 does not have private constructors. This means that you have to create your own method of enforcing the singleton rules.

    David Tucker at December 25th, 2007 around 8:13 pm
    Jump to the top of this page
  25. 25

    Hi from Spain.

    David, great Job. I learn a lot with your tutorials.

    I think there is one error (but I am not sure 100%).

    In this piece of code (inside the constructor of ModelLocator)

    if (enforcer == null) {
    throw new Error( “You Can Only Have One ModelLocator” );
    }
    }

    I think the condition (enforcer == null) is wrong. In mi opinion would have to be (enforcer !=null).

    It´s ok?

    Thanks

    Jose Maria Camara at February 23rd, 2008 around 8:56 am
    Jump to the top of this page
  26. 26

    @Jose - Actually it is correct, but I probably should change the Error message to be more understandable. If you used the method that you just described, the class could not ever be instantiated - because even the class itself could do the instantiation without throwing an error. The Error should read “This Class is a Singleton - please use the getInstance method to return the instance”.

    David Tucker at February 23rd, 2008 around 9:00 am
    Jump to the top of this page
  27. 27

    Yes, You are right. I was thinking in a wrong way

    Jose Maria Camara at February 23rd, 2008 around 9:47 am
    Jump to the top of this page
  28. 28

    Great tutorial. I am getting myself back into Flex and Cairngorm after a 9 month hiatus and this is helping me refresh my memory really well.

    Tony B at February 26th, 2008 around 5:44 pm
    Jump to the top of this page
  29. 29

    Hi David,

    I could not stop reading the articles and watching all the videos one after the other to get an overview of the Cairngorm framework for the past one week. Great series. Really appreciate your efforts…

    Prasad Ganguri at March 8th, 2008 around 5:53 am
    Jump to the top of this page
  30. 30

    Fantastic tutorial David.
    Easy to follow and the video just makes such a difference.
    Sometimes I get a bit lost in spaghetti code and I hope that by getting a handle on some framework ideas I can structure my code better.
    So thanks for your ongoing efforts.

    Ted at March 20th, 2008 around 10:42 am
    Jump to the top of this page
  31. 31

    Thanks for the awesome tutorials

    Chris Brown at March 25th, 2008 around 8:47 pm
    Jump to the top of this page
  32. 32

    [...] Home Hello World with Cairngorm Singleton Pattern with Flex/Cairngorm Cairngorm Video Documents [?] Share This This entry was written by TJ, posted on April 10, [...]

    j4world » Adobe Flex Cairngorm Reference at April 10th, 2008 around 12:53 pm
    Jump to the top of this page
  33. 33

    you rock! this was an awesome tutorial! Helped clear a lot of stuff.. thanks so much again!

    san at April 20th, 2008 around 10:22 am
    Jump to the top of this page
  34. Brian at April 20th, 2008 around 1:10 pm
    Jump to the top of this page
  35. 35

    Wow! Thank you so much for these tutorials.

    Hates_ at April 28th, 2008 around 3:38 pm
    Jump to the top of this page
  36. 36

    [...] David Tucker - Web Development Goodness » Blog Archive » Getting Started with Cairngorm – Part 1 (tags: flex) [...]

    links for 2008-05-06 « sySolution at May 6th, 2008 around 8:34 am
    Jump to the top of this page
  37. 37

    Hello David. Nice tuto. I got a blog that talks about Flex and I’d like to translate this series and publish on my blog. Do you see any problem with that? I will give you the credits, of course.

    Thank you!

    Ved

    Ved at May 16th, 2008 around 6:51 am
    Jump to the top of this page
  38. 38

    Thank you for this great intro to Cairngorm. I’ve only read/watched the first article… and am looking forward to the rest.

    Very nice explanations that make sense, perfect for Flex newbies!

    Sunil at May 16th, 2008 around 5:26 pm
    Jump to the top of this page
  39. 39

    [...] [tradução] Iniciando com o Cairngorm - Parte 1 Créditos: esta série sobre o Cairngorm foi originalmente escrita por David Tucker (www.davidtucker.net), a quem dou todos os créditos. Esta é uma livre tradução do original que pode ser encontrado aqui [...]

    Jump to the top of this page
  40. 40

    Thanks for this. Starting on Tutorial writeup and Video one and sweeping thru all. Very well done.

    Andrew at June 9th, 2008 around 4:37 pm
    Jump to the top of this page
  41. 41

    @Andrew - I am glad that you found it useful!

    David Tucker at June 9th, 2008 around 8:34 pm
    Jump to the top of this page
  42. 42

    [...] Primul episod - Episodul 2 - Episodul 3 - Episodul 4 - Episodul 5 [...]

    FxCodex.ro | Adobe Flex User Group Romania at June 11th, 2008 around 1:06 am
    Jump to the top of this page
  43. 43

    [...] I need to acknowledge David Tucker for this fantastic post that got me [...]

    Jump to the top of this page
  44. Jump to the top of this page
  45. 45

    Thanks for you tuto.

    tiendan at June 22nd, 2008 around 11:02 pm
    Jump to the top of this page
  46. 46

    I try to run it in Flex Builder 3 with SDK flex 3, it has no errors, but it has no output, no windows pop out for result. Any ideas?

    Kevin at June 23rd, 2008 around 7:17 pm
    Jump to the top of this page
  47. 47

    Nice tutorial - you really put some time into it - quality work.

    I’ve been mulling this over for a few days and, I’ve just got to rant:

    I think that adopting the Cairngorm framework for a Flex GUI is a huge mistake for all but maybe 5% of all projects - and even then I question the value…

    I’ve been a developer since back in the client/server days and even beyond that. (i’m geezin’) I’ve come up through the ranks, done my share of web work, J2EE, Struts, Ajax (we used to call it DHTML w/ActiveX), etc., etc.

    What really blows my mind most of all is a Flex front-end is inherently client/server anyway - so why in the world would you possibly need to introduce the complexity of a struts-like framework like Cairngorm to the mix? Client/server has always been a cakewalk compared to web work - and it seems to me that many of those pushing Cairngorm must not have true client/server experience? (this is not a jab - it actually makes sense that, given the age of client/server, that most flex developers have no c/s experience)

    One of the biggest reasons I see repeated as to why a shop should adopt Cairngorm is to allow a “framework” to be put in place that can serve as a jump point for multiple developers… To me, this is just an excuse for the inability of a given project manager to get their team to “think out of the box” about a given project, and come up with a logical design that works for each project.

    Instead of a dev team spending all that extra time thinking about how someone else wants you to write your project, instead of all the time it takes to create and inject all of the extra dependencies and design curves that go into a Cairngorm architecture - just build a normal, robust client/server project and spend that extra time on design and documentation of that design - a real no-brainer…because you have to take those two steps no matter what architecture you settle on. If you’ve developed a solid EJB middle-tier that properly manages concurrency and load, the GUI tier should snap right into place with a simple GUI API like Flex.

    I’ve never heavily bought into “frameworks” and never will - why? Gee - look at all those “great frameworks” out there, look how often they get scrapped for the “next version” or a “better mousetrap”…history proves this fact time and time again. Now that Flex is starting to become more accepted in general development over a larger developer audience, it’s a certainty that Cairngorm will be scrapped soon enough for a better mousetrap, etc., etc.

    Cheers, Eric.

    Eric Holsinger at July 3rd, 2008 around 12:49 pm
    Jump to the top of this page
  48. 48

    Thanks Eric for your thoughts, I look forward to seeing what the future will hold.

    Nikos Katsikanis at July 14th, 2008 around 10:35 am
    Jump to the top of this page
  49. 49

    Excellent tutorial. Clear understanding for using Cairngorm.

    Charlene Dougall at July 14th, 2008 around 11:48 am
    Jump to the top of this page
  50. 50

    [...] at the Cairngorm framework. I found a link to David Tucker’s excellent video tutorials, which begin here, and initially I was really keen on what I saw. The widespread adoption of this framework was a big [...]

    Jump to the top of this page
  51. 51

    [...] Getting Started with Cairngorm - Part 1 [...]

    CuriousFind » Blog Archive » Notes on learning Cairngorm at September 12th, 2008 around 11:23 am
    Jump to the top of this page
  52. 52

    Now here is a clear, smart, well-paced tutorial. I have got me hooked. Thanks so much for doing all this.

    Regis Zaleman at September 14th, 2008 around 7:25 am
    Jump to the top of this page
  53. 53

    Hi

    Congratulations, you made a great job on these tutorials.
    I’m using Flex Builder 3.0.1 (August milestone), and I was having a little problem with the code, as a warning popped out for lack of binding in the modelLocator private variable. The solution I found as just making it Bindable, as follows:

    import net.inoventos.ContactManager.model.SampleModelLocator;
    [Bindable]
    private var modelLocator:SampleModelLocator = SampleModelLocator.getInstance();

    Please tell me if this is some change over the version of Flex Builder you used when making the tutorial.

    Thanks

    João Pedro Bourbon at September 16th, 2008 around 1:27 pm
    Jump to the top of this page
  54. 54

    Ok, forget it, I see you tackled this issue in part 2 :D

    João Pedro Bourbon at September 17th, 2008 around 9:09 am
    Jump to the top of this page
  55. 55

    David,

    Nice job on the Cairngorm tutorials. I do have a question. Why did you use an enforcer for the singleton class instead of just making the constructor private? A benefit of making the constructor private is that the compiler will be able to catch you if you try to create an instance of the class whereas in the enforcer method you don’t get any errors until runtime which is not as desirable.

    Thx,

    Fred

    Fred R. at September 21st, 2008 around 7:42 am
    Jump to the top of this page
  56. 56

    @Fred R. - Unlike Java, ActionScript 3 does not have private constructors. All constructors are public in AS3.

    David Tucker at September 21st, 2008 around 8:40 am
    Jump to the top of this page
  57. 57

    Thanks for the reply.

    I don’t understand why AS3 doesn’t support a private constructor. From a lang. design point of view I don’t see any benefit in not allowing a private constructor.

    Fred R. at September 21st, 2008 around 9:37 am
    Jump to the top of this page
  58. 58

    Dude ,
    No doubt very best efforts to teach us important think like to dump like me ;)
    love u

    Sajid hussain at September 25th, 2008 around 3:41 pm
    Jump to the top of this page
  59. 59

    [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

    Adobe Flex - Cairngorm « Panduramesh’s Weblog at September 29th, 2008 around 2:44 am
    Jump to the top of this page
  60. 60

    [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

    anil4it at September 30th, 2008 around 5:13 am
    Jump to the top of this page
  61. 61

    [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

    Anilkumar at September 30th, 2008 around 5:40 am
    Jump to the top of this page
  62. 62

    [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

    Flex with Cairngorm « It’s all about RIA at October 13th, 2008 around 10:20 pm
    Jump to the top of this page

Leave a Reply

  •  
  •  
  •  

You can keep track of new comments to this post with the comments feed.

Badges

View David Tucker's profile on LinkedIn
Inside RIA Badge

Community Posts