Flex Blog

Search:
  • Home
  • Examples
    • Thumb

      Flex Examples

      Check out our Flex Examples!

    • Thumb

      Flash Builder Examples

      Check out our Flash Builder Examples!

    • Thumb

      AIR Examples

      Check out our AIR Examples!

    • Thumb

      Flex Mobile Examples

      Check out our Flex Mobile Examples!

    Adobe® Flex, Adobe® Flash Builder and Adobe® AIR are registered trademarks of Adobe Systems.
  • Components
    • Thumb

      WP Flex Contact Form

      Check out our WP Flex Contact Form!

    • Thumb

      Flash CountDown Plugin

      Check out our Flash CountDown Plugin!

    This is an overview of all our Flash/Flex based Components.
  • Jobs
  • Flex Books
  • Forum
  • Contact Us
Subscribe to Flex BlogSubscribe
  • Examples
  • iOS
Browse > Home / Examples / SWIZ Framework in Flex 4 Example: Part I

SWIZ Framework in Flex 4 Example: Part I

06 August 2010

Line Break

Author: Arjan (47 Articles) - Author Website

Arjan is a SAP Consultant specialized in ABAP and Front End development techniques like Web Dynpro, Adobe Interactive Forms, Flex and AIR. In his free time he likes to create examples for Flex-Blog and other applications using Flex, AIR and PHP. Other hobbies are movies and music. He is also the co-owner of Flex-Blog.com.


A few weeks ago I posted about the SWIZ Framework. The post was useless, but I was so enthusiastic about SWIZ, that I had to post something at that time. This post will be more usefull, I promise. Lets see how we can get the SWIZ Framework working in combination with the Flex 4 SDK.

First, you may want to find out about flex frameworks, MVC(S) in general if you don’t know anything about them. Its really helpful to have some sort of understandig why we want to do things using the MVC paradigm and how we can use frameworks to help us to achieve that.


Try to understand the basics of flex frameworks (Cairngorm, PureMVC, SWIZ etc. etc.) and MVC(S) by reading about them before you start developing applications. As I found out, understanding the concepts is really important. Just visit some framework / MVC sites and wiki’s to get a basic understanding.


Im not gonna talk about the pro and cons of certain frameworks here. All I know is that I know a few of them and SWIZ is the only one that I really like for a few simple reasons:

  • It doesn’t slow down you development time at all
  • Easy to understand
  • Easy to apply
  • Its MVC(S), but that applies to all the major frameworks

Now enough about all that, lets create a simple application with MySQL, PHP and Flex 4 using SWIZ. First, you will need the SWIZ swc file, at this time, the latest release is 1.0 RC1, you can download it here.

Lets discuss the functional specs of our mini flex application briefly before we start building it. What I want is the following:

Storage:

  • Store company data (name and location)
  • Store contact persons for companies (firstname, lastname)

Application:

  • List of companies showing name and location
  • List of contact persons of the selected company (loaded when user selects a company).

This post, Part I will only cover the first item in our list. In part II, we are going to handle item two in our list.

Let’s get started. First, we’ll need some database and two tables to facilitate this. In this example we are using PHP and MySQL so I used PHPMyAdmin to create the following:

  • A table company which has 3 fields: id (int, auto increment primary key), name (text 100) and location (text 100)
  • A table contactperson which has 4 fields: id (int auto increment primary key), companyid (int), firstname (text 100) and lastname (text 100).

Add some dummy data to both tables using phpMyAdmin.

When you’re finished you’re ready to start coding in Flex. Start your Flash Builder 4 and create a new project (in my case I called it SimpleSWIZExamplePart1).

After that, add the SWIZ swc file to you libs folder inside your project folder. You can just drag and drop it from your filesystem to do this. Now you’re all set to start using SWIZ. First, lets add the basic configuration to our main application file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<fx:Declarations>
   
    <swiz:Swiz beanProviders="{[]}">
       
        <swiz:config>
            <swiz:SwizConfig setUpEventType="creationComplete"
                             setUpEventPhase="{ EventPhase.CAPTURING_PHASE } "
                             setUpEventPriority="50"
                             tearDownEventType="{ Event.REMOVED_FROM_STAGE }"
                             tearDownEventPhase="{ EventPhase.CAPTURING_PHASE }"
                             tearDownEventPriority="50"
                             strict="true"
                             viewPackages="com.flexblog.swizexample.view.*"
                             defaultFaultHandler="onFault"
                             defaultDispatcher="dispatcher" />
        </swiz:config>
       
    </swiz:Swiz>
   
</fx:Declarations>

Notice that you can set some properties, the most important one is viewPackages. Later on, you’ll have to specify your own package here. Notice that there’s a defaultFaultHandler in the configuration which calls a function onFault, this requires a tiny bit of script in your main application file:

1
2
3
4
5
6
7
8
9
10
11
<fx:Script>
    <![CDATA[
        import mx.controls.Alert;
        import mx.rpc.events.FaultEvent;
       
        private function onFault(event:FaultEvent):void
        {
            Alert.show( event.fault.message, "Error" );
        }
    ]]>
</fx:Script>

First we’re going to create our application model. Create a package structure first, for example com.flexblog.swizexample. In that package, create another package called model. Inside that model package, create an ActionScript class called Model.as. This class is going to be our central data store in the application. Here’s the code for the initial model class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.flexblog.swizexample.model
{  
    import mx.collections.ArrayCollection;

    public class Model
    {
        /**
         * List of companies
         */

        [Bindable]
        public var companies:ArrayCollection;

        public function Model()
        {
        }
    }
}

As you can see, the model has on variable called companies, this is going to hold the list of companies that we retrieve from the backend using a service (which is called by a controller). You still with me? Let create the ActionScript service that communicates with the backend.

To create the service, we can use one of the great new features of Flash Builder 4 to connect with out database. Click on the data button in Flash Builder 4, select Connect to PHP and click the generate sample link. Connect to your local mysql server. In my case: user / pass, hostname: localhost, port: 3306. After that, select the company table. Flash Builder automatically generates a PHP file for you that communicates with the back-end! Make sure you give the service an appropriate name (e.g. CompanyService) and put your newly created actionscript class in a services package, for example com.flexblog.swizdemo.services, for the datatype package, use com.flexblog.swizexample.domain.

Now to execute this service, we are going to create a Controller. Create a new package called controller inside your “main” package. In my example the package is com.flexblog.swizexample.controller. Inside the package, create a new ActionScript class called CompanyController.as. Put the following code in the class:

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
41
42
43
44
45
package com.flexblog.swizexample.controller
{
    import com.flexblog.swizexample.model.Model;
    import com.flexblog.swizexample.services.CompanyService;
       
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
   
    import org.swizframework.utils.services.ServiceHelper;

    public class CompanyController extends AbstractController
    {
        /**
         * companyService, Injected by SWIZ Framework
         */

        [Inject]
        public var companyService:CompanyService;
       
        public function CompanyController()
        {
        }
       
        /**
         * Automatically called by SWIZ Framework after
         * application startup by using the [PostConstruct] tag
         */

        [PostConstruct]
        public function getAllCompanies():void
        {
            sh.executeServiceCall( companyService.getAllCompany(), handleGetAllResult, handleFault );
        }
       
        private function handleGetAllResult(event:ResultEvent):void
        {
            model.companies = event.result as ArrayCollection;
        }
       
        private function handleFault(event:FaultEvent):void
        {
            Alert.show( event.fault.message, "Error" );
        }
    }
}

Notice the [PostConstruct] tag above the getAllCompanies() method. This nice SWIZ metadata tag lets SWIZ know that it should automatically execute the method decorated with that tag on application startup. Very nice!

As you can see, the CompanyController extends a Class called AbstractController which holds some things that all my Controllers are going to need, create that class as well:

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
package com.flexblog.swizexample.controller
{
    import com.flexblog.swizexample.model.Model;
   
    import org.swizframework.utils.services.ServiceHelper;
   
    public class AbstractController
    {
        /**
         * ServiceHelper to facilitate service calls, Injected by SWIZ Framework
         */

        [Inject]
        public var sh:ServiceHelper;
       
        /**
         * Application model, Injected by SWIZ Framework
         */

        [Inject]
        public var model:Model;
       
        public function AbstractController()
        {
        }
    }
}

Now we need to do some additional things to make these classes work. As you can see i’m using variables called companyService, model and serviceHelper which are never instantiated…here’s where SWIZ helps you with a great little thing called Dependency Injection: it automatically creates an object of type CompanyService for you when it’s needed. Strange when you see it for the first time but it helps you A LOT.

To let SWIZ tie everything together, we need something called a BeanProvider. Create a new MXML component called Beans.mxml in you main package (com.flexblog.siwzexample) based on anything and replace all the code with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<swiz:BeanProvider xmlns:fx="http://ns.adobe.com/mxml/2009"
          xmlns:s="library://ns.adobe.com/flex/spark"
          xmlns:mx="library://ns.adobe.com/flex/mx"
          xmlns:swiz="http://swiz.swizframework.org"
          xmlns:controller="com.flexblog.swizexample.controller.*"
          xmlns:services="com.flexblog.swizexample.services.*"
          xmlns:model="com.flexblog.swizexample.model.*" >

        <controller:CompanyController id="companyController"/>
        <services:CompanyService id="companyService"/>
        <swiz:ServiceHelper id="serviceHelper"/>
        <model:Model id="model"/>
   
</swiz:BeanProvider>

With this, SWIZ knows that it should do Dependency injection on all Objects of type Model, CompanyController, CompanyService and ServiceHelper when the variables have the [Inject] metadata tag.

Now with that out of the way lets set up a view that can display our company details. First, create a view package that can hold all your MXML view components. In my example the package is com.swizexample.view. After that, create a new MXML component inside that package called MainView.mxml. Make sure it’s based on a VGroup and remove the height and width details. After that, create a new MXML component called CompanyView.mxml, also based on a VGroup, remove the width and height here too.

Now you should have 2 new MXML components. Add the MainView.mxml to your application file like this:

1
<view:MainView id="mainView" width="100%" height="100%"/>

And add the CompanyView to your mainview:

1
<view:CompanyView id="companyView" width="100%" height="100%"/>

Ok, now lets finish our CompanyView, we will just add a basic DataGrid to list all companies with a simple title to it:

1
2
3
4
5
6
7
8
<s:Label text="Companies" fontWeight="bold"/>
<mx:DataGrid dataProvider="{model.companies}"
             width="100%" height="100%">
    <mx:columns>
        <mx:DataGridColumn headerText="Name" dataField="name"/>
        <mx:DataGridColumn headerText="Location" dataField="location"/>
    </mx:columns>
</mx:DataGrid>

As you can see, the CompanyView uses model.companies as the dataprovider for the datagrid. To make it a bit more complicated, this is not the model we discussed earlier. This model is acutally a new ActionScript class called CompanyViewPresentationModel.as which is going to be the Presentation Model of our CompanyView. Still with me? Create a new subpackage in the model package called presentation. Inside that package, create the CompanyViewPresentationModel.as class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.flexblog.swizexample.model.presentation
{
    import mx.collections.ArrayCollection;

    public class CompanyViewPresentationModel
    {

        /**
         * List of companies, injected and binded to the application model using SWIZ
         */

        [Bindable]
        [Inject(source="model.companies", bind="true")]
        public var companies:ArrayCollection;
       
        public function CompanyViewPresentationModel()
        {
        }
    }
}

As you can see it also has a companies variable. This companies variable is binded to the global model (Model.as) using the SWIZ [Inject(source="model.companies", bind=true)] tag.

Also add this new Class to your Beans.mxml file so that SWIZ can Inject this in your view.

1
<presentation:CompanyViewPresentationModel id="companyViewPresentationModel"/>

Now add the following to your CompanyView:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<fx:Script>
    <![CDATA[
        import com.flexblog.swizexample.model.presentation.CompanyViewPresentationModel;
       
        /**
         * The presentation model for the CompanyView,
         * Injected by SWIZ
         */

        [Inject]
        [Bindable]
        public var model:CompanyViewPresentationModel;

    ]]>
</fx:Script>

Ok, now you’re ready to finish configuring SWIZ in your application file. Add the Beans.mxml to the swiz config (and import the Beans.mxml in the script section) and make sure the viewPackages property is ok:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<fx:Declarations>
   
    <swiz:Swiz beanProviders="{[Beans]}">
       
        <swiz:config>
            <swiz:SwizConfig setUpEventType="creationComplete"
                             setUpEventPhase="{ EventPhase.CAPTURING_PHASE } "
                             setUpEventPriority="50"
                             tearDownEventType="{ Event.REMOVED_FROM_STAGE }"
                             tearDownEventPhase="{ EventPhase.CAPTURING_PHASE }"
                             tearDownEventPriority="50"
                             strict="true"
                             viewPackages="com.flexblog.swizexample.view.*"
                             defaultFaultHandler="onFault"
                             defaultDispatcher="dispatcher" />
        </swiz:config>
       
    </swiz:Swiz>
   
</fx:Declarations>

That should be it. Try running your application. If everything is ok, you should see a list of companies from your local database (if you added the dummy data, ofcourse).

Something like this, view source is enabled. Check out the ASDoc here:

Related posts:

  1. SWIZ Framework in Flex 4 Example: Part II
  2. The SWIZ framework for Flex 3 / Flex 4: Easy, Light and Very Powerfull
  3. How to make a magnetic button in Flex 4
  4. Flex Custom Event Example

Written by Arjan · Filed Under Examples 

Was this post useful to you?

Please rate this post, follow us @ twitter, or link to this page from your website!

1 Star2 Stars3 Stars4 Stars5 Stars (11 votes, average: 3.91 out of 5)
Loading ... Loading ...

be82e2e3bd63be541fb3440b6d14d619delicious

Comments

12 Responses to “SWIZ Framework in Flex 4 Example: Part I”

  1. SWIZ Framework in Flex 4 Example: Part I : Flex Blog | Flex learner on August 6th, 2010 11:26 pm

    [...] more here: SWIZ Framework in Flex 4 Example: Part I : Flex Blog This entry was posted in Flash, Flash Builder 4.0 and tagged builder, connect, connect-with, [...]

  2. Haydex Kadhim on August 21st, 2010 4:03 am

    Great Arjan, I really wondered how to use the data centric features of Flash Builder 4 to work in Swiz framework, again, greate article man!

  3. Arjan on August 21st, 2010 12:51 pm

    Thnx, always nice to know that someone actually appreciates an article on http://www.flex-blog.com!

  4. Terrenc on August 28th, 2010 4:35 pm

    I’m kind of stumped on why I get this error for this line statement decleration

    “Could not resolve to a component implementation.”

    X?

    I desided to drop in the swc that comes with your project, it did solve 75% of the Warnings but still the same error, have any suggestions?

  5. Arjan on September 6th, 2010 10:28 am

    You need the SWC file for the SWIZ Framework. The message states that it can’t find the base class for a certain component and/or Class. Maybe you’re missing an import statement somewhere or a namespace binding somewhere in a Class / MXML component.

    Let me know if this helps.

  6. Gaston on December 15th, 2010 6:22 pm

    I get the same ‘Could not resolve to a component implementation’ in my Beans.mxml file.

    I do have the swc file in my libs. What else could it be?

  7. webdpi on January 25th, 2011 4:02 am

    Arjan,
    Excellent article. Gave me a good start. Thanks verymuch!!!

  8. Arch Brooks on February 22nd, 2011 4:56 am

    This example produced a compile error as diagramed in this article. I am using Flash Builder 4 (SDK 4.1). My other Swiz articles work fine with this combination. I recommed you produce the project.fxp to avoid this level on confusion in the future.

  9. Srini on September 28th, 2011 7:00 am

    Good article!!!! for the starters….

  10. Iain on October 18th, 2011 12:55 am

    great article, however I couldn’t get the example to compile – it gave me an undefined method error against the getAllCompany() method.

    Any ideas?

  11. Swanand reddy on November 24th, 2011 5:48 am

    Hi Arjan,

    Thanks a lot for this tutorial. I have been able to follow this tutorial to finish but in my main application I get an error: ’1120: Access of undefined property Beans.’

  12. Swanand reddy on November 24th, 2011 6:24 am

    Ok the problem is that I havent import the bean in the main app. Thanks

Get Adobe Flash player

  • +1?

  • Support Flex Blog!

  • $ 13 raised
    • 2012/01/13 8:22 PM Russell Brown donated $ 3.00
    • 2011/10/31 4:43 PM Steve Dakin donated $ 5.00
    • 2011/05/11 3:37 PM Roelof Albers donated $ 5.00
  • Stay in touch!

  • Popular Tags

    • AdvancedDataGrid
    • AIR
    • ArrayCollection
    • baseColor
    • Button
    • CursorManager
    • DataGrid
    • Dynamic
    • Effects
    • File
    • FileStream
    • Flash Builder
    • Flash Builder 4
    • Flex 4
    • Flex Mobile
    • Framework
    • Icon
    • Image
    • itemRenderer
    • LinkBar
    • Mobile
    • PHP
    • ProgressBar
    • Repeater
    • Style
    • SWIZ
    • Timer
    • Tree
    • Twitter
    • ViewStack
  • Advertisements

  • Recent Posts

    • Spooky Frenzy – iPad Game
    • Fountain Example
    • Reading & Writing files in Adobe AIR
    • CheckBox in List using MobileIconItemRenderer for Flex Mobile
    • Data Dependent decoratorClass in MobileIconItemRenderer Example
    • Flex 4 Resize Effect Example
    • Jump to next field using the Focus Manager
    • Searching Data using a Class Example
    • Flex Mobile: Two finger tap gesture to toggle actionBar visibility in a View (AIR for Android)
    • TabbedMobileApplication Example in Flex Mobile (AIR for Android)
  • Categories

    • Examples
    • Guest Poster
    • iOS
  • Archives

    • September 2011
    • July 2011
    • May 2011
    • March 2011
    • February 2011
    • November 2010
    • October 2010
    • September 2010
    • August 2010
    • June 2010
    • May 2010
    • April 2010
    • March 2010
    • February 2010
    • January 2010
    • December 2009
    • November 2009
    • October 2009
    • March 2009
    • February 2009
  • Blogroll

    • Adobe Flex Jobs
    • NL for Business
  • Meta

    • Register
    • Log in
    • WordPress
    • XHTML

Copyright © 2010 Flex Blog · AdobeĀ® and AdobeĀ® Flex are registered trademarks of Adobe Systems.

WordPress Adobe Flex Adobe Flash Builder Adobe AIR Creative Commons License

  • Popular Posts

    • Progressbar in Datagrid Example 13 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Data Dependant Tree Icon with Tree in AdvancedDataGrid with iconFunction 8 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 5 (5.00 out of 5)
    • List Directory with AIR in Flex 4 7 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Flex FlashVars in AS3 Example 7 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Flex Dynamic Chart Example 4 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 5 (5.00 out of 5)