Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Languages

  • submit to reddit

Application Performance Testing: From Conception to Gravestone

0 replies - 1285 views - 12/05/11 by Brandon Nokes in Whitepapers

Why Load Testing From The Cloud Doesn't Work

0 replies - 1243 views - 12/05/11 by Brandon Nokes in Whitepapers

Web Load Testing is Good Business

0 replies - 1293 views - 12/05/11 by Brandon Nokes in Whitepapers

Flex Mobile Development

Build Apps for Android, iOS, and BlackBerry Tablet OS

By Mihai Corlan

9,704 Downloads · Refcard 146 of 151 (see them all)

Download
FREE PDF


The Essential Flex Mobile Cheat Sheet

The Flex Mobile Development cheat sheet will walk you through the easiest process yet for developing and deploying cross-platform applications on multiple devices and platforms with the richness that you expect out of an Adobe creative tool. You can now develop mobile ActionScript and Flex applications for Google Android, Apple iOS, and BlackBerry Tablet OS with the same ease and quality as on desktop platforms, and with most of the same code! Get a rundown of the new Flash Builder 4.5s mobile app capabilities through a series of sections on app creation, mobile packaging, testing, and debugging.
HTML Preview
Flex Mobile Development: Build Apps for Android, iOS, and BlackBerry Tablet OS

Flex Mobile Development:Build Apps for Android, iOS, and BlackBerry Tablet OS

By Mihai Corlan

Adobe® Flash® Builder™ is an integrated development environment (IDE) based on the Eclipse platform. Available for Windows and Mac, it is used for creating Flex and Flash applications accessible via a web browser with Flash Player or as standalone apps.

Because it is based on the Eclipse platform (version 3.6.1), it can be installed as a standalone IDE or as a plug-in within another Eclipse installation.

You can run this version along with previous versions (Flash Builder 4 or Flash Builder 3) without any problems.

This version comes in two flavors: standard or premium. Each flavor is also available as Flash Builder 4.5 for PHP, which has all the features of Flash Builder plus Zend Studio 8.1 and a number of plug-ins that integrate these two IDEs.

Flash Builder Premium provides the following features in addition to those included with the standard version:

  • Network Monitor
  • Memory Profiler
  • HP QuickTest Professional and FlexUnit integration
  • Command-line support for automated build processes
  • ColdFusion Builder (an Eclipse-based IDE for ColdFusion application developers)

You can download Flash Builder 4.5 from here and Flash Builder 4.5 for PHP from here. Select the installer for the version you are interested in and for your operating system. The same installer can be used for installing the standalone version or the plug-in version.

Each version offers a 60-day trial period. Every time you start the product during the trial period you will see a reminder that enables you to buy the product or enter the serial number if you’ve already bought it.

To enable support for BlackBerry Tablet OS development you’ll have to download an Eclipse plug-in from RIM. Once installed in Flash Builder 4.5, this plug-in will enable a new platform target.

What’s new in Flash Builder 4.5

Here is a high level view of what is new in this release:

Support for mobile development. Flex 4.5 version marks the extension of the Flex framework to mobile development. Flash Builder 4.5 includes several mobile-specific features, including new project types, desktop simulation and design view, and support for packaging projects as native installers for Android, iOS, and BlackBerry Tablet OS.

Improved productivity. Code templates, quick assist, code hinting for metadata, and an improved profiler.

Expanded PHP support. Flash Builder for PHP integrates Zend Studio with Flash Builder:

  • New wizards for creating Flex and PHP projects for desktop or mobile.
  • Integrated debugging for PHP and Flex.

Flash Builder 4.5, Flex 4.5, and the screen metaphor

While it is possible to create mobile applications using pure ActionScript and Flash Builder 4.5, developing mobile apps using the Flex 4.5 framework, with its support for the screen metaphor, provides a substantial productivity boost.

There is almost always enough resolution and area on a desktop computer to fit all the information you want on the screen. By using hierarchical menus and pop-up windows you can fit even more content. Compared to this, a smartphone screen feels (almost) like a postage stamp. Besides screen size, pixel density plays an important role. The Nexus One, for example, has a resolution of 480 x 800 pixels and 254 pixels per inch. This means that you have to enlarge the text roughly two to four times to make it appear similar to the app running on a desktop or laptop screen. Thus you end up with less space to display information.

Window 1

Using the screen metaphor you can split the information and the UI of your application among multiple screens. For example, consider the MAX Companion 2010 app, which shows conference session information. When you want to see details for a particular session (see the images above) another screen is presented. When you return to the previous screen, the session list is shown again.

Elegant as it might be, writing an app using the screen metaphor is not rocket science. However, there are some issues to be considered, such as:

  • Memory management – pushing dozens of screens can consume all the memory available on the device
  • Transitions from one screen to another – nice effects will help you create an application like a professional UX Designer
  • Passing data from one screen to another – you need some way of exchanging data between screens
  • Preserving application state – when the OS closes your app, you’ll want to save its state to restore when it reopens
  • Integration with hardware buttons – you press the Back button of the device, for example, to navigate to the previous screen

The Flex framework has built-in support for the screen metaphor so you don’t have to reinvent the wheel as you address these issues

Supported mobile platforms

The June 2011 release of Flash Builder 4.5 and the Flex 4.5 SDK support Android, iOS, and BlackBerry Tablet OS. The initial launch (in May 2011) supported Flex development for Android only, although you could still develop pure ActionScript apps for all three platforms (Android, iOS, and BlackBerry Tablet OS).Applications created in Flash Builder run differently depending on the target platform:

  • On Android and BlackBerry Tablet OS the APK or BAR files are run using the Adobe AIR runtime installed on the devices. PlayBook devices (running BlackBerry Tablet OS) come with Adobe AIR pre-installed. Some Android devices have Adobe AIR pre-installed, while others don’t. If AIR is not installed already, you will be prompted to install it from the Android Market the first time an AIR application is opened.
  • On iOS, the application is cross-compiled to a native IPA file together with the Adobe AIR runtime.

FLASH BUILDER 4.5 MOBILE PROJECT TYPES

When you choose File > New in Flash Builder 4.5, you will see two new mobile applications project types to choose from: ActionScript Mobile Project and Flex Mobile Project.

In Flash Builder for PHP you’ll see those two types plus one more for creating a Flex Mobile and PHP project.

CREATING A FLEX MOBILE PROJECT

To use the Flex framework to create a mobile app:

  1. 1choose File > New > Flex Mobile Project. In the first page of the wizard, specify the project name.
  2. Window 2
  3. In the second page of the wizard, choose the target platforms. In the following image, BlackBerry Tablet OS and Google Android are selected; in the June 2011 release you can also select iOS. You can also use the Permissions tab on this page to set additional mobile application permissions for Android and BlackBerry Tablet OS. In the Application Template tab you’ll see three options: Blank, View-Based Application, and Tabbed Application. If you want Flex support for the screen metaphor, choose either View-Based Application or Tabbed Application. The Tabbed Application option is preferable if your application has lots of screens and you want to use a tab group at the bottom of the page to group these screens.

    if you choose Blank, you can use Flex components but you will have to handle events such as device orientation changes or pressing the Back button on an Android device yourself.

    When creating a Flex mobile and PHP project with Flash Builder 4.5 for PHP (File > New > Flex Mobile and PHP Project), the process is quite similar except you also set up a PHP project at the same time:
Window3

  • The second screen is for setting up the Flex project
  • The third screen is for setting up mobile specific settings

You can watch my video tutorial on this topic. Creating an ActionScript mobile project is similar to the Flex one.

Understanding Flex mobile View and ViewNavigator class

If you choose to use View-Based Application or Tabbed Application, it is important to understand the following classes: View, ViewNavigator, ViewNavigatorApplication, and TabbedViewNavigatorApplication.

The top application class will be ViewNavigatorApplication or TabbedViewNavigatorApplication depending on the Application Template you used when creating the project. You create your application user interface by extending the View class. Basically each screen of your application will be represented by a component that extends the View class. To create a new screen, choose File > New > MXML Component and then set the spark.components.View class as the class to base the component on.

The View class has two important properties: data and navigator. You use the navigator property (which refers to an instance of the ViewNavigator class) to control the screens. When you want to push a new view to the screen, you call navigator.pushView(new-viewclass- name). When you want to return to the previous view, you call navigator.popView(). When you want to jump to the first view you call navigator.popToFirstView().If you don’t want to have the View destroyed, you can set the destructionPolicy attribute of the View tag to “never”.

To pass data from the current View to the next one, simply set the second argument of the pushView() method to the data you want to pass; for example, navigator.pushView(view-class-name, dataToBeUsed); There are some applications that need to preserve their entire state when they are closed by the OS. To do this, just set the persistNavigatorState attribute in your main application file to true. This is a neat feature that allows you to support (with almost no effort) scenarios in which the user has navigated several screens into the application when the application gets closed (for example if the user switched to a new application or decided to close the app); when the application opens again, the user will see the same screen as in the previous session.

There are also events you can listen for in each View:

  • viewActivate (FlexEvent.VIEW_ACTIVATE) – Dispatched when the current view has been activated.
  • viewDeactivate (FlexEvent.VIEW_DEACTIVATE) – Dispatched when the current view has been deactivated.
  • removing (FlexEvent.REMOVING) – Dispatched when the screen is about to be removed in response to a screen change. If you call preventDefault() you can cancel the screen change. This event is triggered before the FlexEvent.VIEW_DEACTIVATE event.

TESTING AND DEBUGGING MOBILE PROJECTS

One of the most powerful features of Flash Builder 4.5 is its ability to run mobile projects right from the IDE. If you have a physical device you can deploy the app and debug on the device from Flash Builder

If you don’t have a device you can use the Flash Builder simulator to test the app. In either case, you start by choosing Run > Running Configuration or Run > Debug Configurations.

To add a new configuration, select the Mobile Application entry (or Mobile (PHP) Application if the project type is Flex Mobile and PHP) and then click the top-left icon to add a new configuration. Select the project that you want to create the configuration for and then select the Target Platform (Android, iOS, or BlackBerry Tablet OS).

Window4

For the Launch Method, select On Desktop if you want to run the app on the desktop simulator or select On Device if you want to deploy the app to the device. The simulator is quick and easy to use. Using the second option—On Device—is less straightforward; depending on the target platform you will need certificates, provisioning files, debug tokens, and so on. For both options you can run the application with or without debugging support.

PACKAGING A MOBILE PROJECT AS A MOBILE APP

Flash Builder 4.5 supports packaging your mobile projects (ActionScript or Flex) as native applications that is, as an APK for Android, an IPA for iOS, or a BAR for BlackBerry Tablet OS.

To access this feature, select the project for which you want to create the native app, choose File > Export, and select Flash Builder > Release Build.

Window5

Follow the directions on screen for the rest of the process, which is different for each supported target (Android, BlackBerry Tablet OS, or iOS).

Packaging mobile apps for Android

To package a mobile app for Android, right-click the project name in the Package Explorer view and select Export > Flash Builder > Release Build. On the first page of the wizard make sure you select the Google Android platform and select Signed Package For Each Target Platform.

Window6

On the second page of the wizard in the Digital Signature section, click Create to begin creating a self-signed certificate. Type the publisher name, organizational unit, organizational name, and country. Select 2040-RSA for the type, set the password, and specify the location and the file name for the certificate. When you click OK, Flash Builder will create the certificate. When you complete the wizard by clicking Finish, Flash Builder will create the APK file. By default, the APK file is created inside the root of your project. You can upload this file to the Android Market.

Window7

Every time you want to release an update for your application, first increase the versionNumber in your application descriptor file and then use the same workflow to create the APK. This time, however, instead of creating a new certificate, just select the one you created earlier.

Packaging mobile apps for BlackBerry Tablet OS

There are two main steps you have to complete to package AIR projects for BlackBerry Tablet OS:

  • Request permission from RIM to sign BlackBerry Tablet OS apps and get the CSJ registration files.
  • Configure Flash Builder for signing PlayBook apps and sign your application.

The credit card is required only for verification purpose. Once you finish this registration you will receive a confirmation email. Then, you should receive by email a number of CSI and CSJ files within 24 hours. Save all these files in the same folder. (Note that the number part of the filename is different for each registration). If you forget the PIN or if you want to sign from another computer, you can submit another request.

Package the project for PlayBook

Once you have the files from RIM, you are ready to use Flash Builder 4.5 to sign mobile ActionScript and Flex projects. Begin by opening the Preferences dialog box (choose Window > Preferences). Then expand the Flash Builder entry on the left side and choose Target Platforms > BlackBerry Tablet OS > Signing.

The top section is for providing a developer certificate for signing the code. To create one, click Create Certificate. Pay attention to what password you set and what value you set for the Publisher–this value must be the same as the one you provided when requesting permission to sign PlayBook apps. When you click OK in the Create Developer Certificate dialog box, a new certificate will be generated. Now, add this certificate by clicking the Select Certificate button.

Window8

Next you need to register and configure the RIM certificate. First click Create in the RIM Certificate section and set a password (it must be at least 6 characters long). Then click the Register button, select the last of the five CSJ files you received via email, and provide the same PIN you set when you completed the online form. Flash Builder will communicate with RIM servers (this step requires you to have your computer connected to the Internet) to register your RIM certificate.

Next you need to register and configure the RIM certificate. First click Create in the RIM Certificate section and set a password (it must be at least 6 characters long). Then click the Register button, select the last of the five CSJ files you received via email, and provide the same PIN you set when you completed the online form. Flash Builder will communicate with RIM servers (this step requires you to have your computer connected to the Internet) to register your RIM certificate. To save the configuration, click OK.

Window9

After you’ve registered your certificates with the BlackBerry Signing Authority you should receive an email confirmation. The next step is to open the application descriptor file for your project in Flash Builder and make sure you set a version number for <versionNumber>. Each time you export a release build you’ll have to increase this number. Next, open the blackberry-tablet. xml file and make sure that the value for the <publisher> node is the same as the one you set for the company value when you registered for signing PlayBook apps and when you generated the developer certificate. Then right-click the project name in the Package Explorer view and select Export.

In the wizard that opens, select Flash Builder > Release Build and click Next. In the second page of the wizard make sure you select BlackBerry Tablet OS in the Target Platforms section. By default the BAR file will be created in the root folder of the project you are exporting. If you want to use a different path, type a new Export To Folder value. You also need to select Export And Sign A Platform-specific Application Package. Click Next.

Window10

In the third page of the wizard select Enable Digital Signing on the Digital Signature tab. This option will use the certificates (Developer and RIM) you set earlier. Finally, click Finish.

Window11

After a few seconds you should have a new BAR file. If you encounter any errors, see BlackBerry’s page on application signing errors for additional information.

You can submit the BAR file to the BlackBerry App World portal (if you have registered as a vendor) via https://appworld.blackberry. com/isvportal/.

Packaging mobile apps for iOS

To package applications for testing and debugging on iOS devices or for deployment to the Apple App Store you will need to enroll in the Apple Developer Program (fees apply). For more information on the Apple Developer Program and to create an account, visit Apple’s Developer Program Enrollment page.

Once registered, you will need to login to the iOS Provisioning Portal and complete the following tasks:

  • Generate a development certificate
  • Register any devices to which you wish to deploy applications during development
  • Define an App ID for the application you are developing
  • Create a development provisioning profile

You will also use the iOS Provisioning Portal to distribute your application via the App Store. That part of the process is not covered in this article; instead refer to Apple’s documentation. The development certificate (in P12 format) and the provisioning profile are required before you can package your application for iOS in Flash Builder.

Generate a development certificate

Follow the guide on the iOS Provisioning Portal to generate your development certificate. This guide assumes you are using a Mac OS based computer, but it is possible to generate the certificate using Windows; details are available in the Adobe AIR documentation.

Convert the developer certificate into a P12 format

To use the certificate with Flash Builder, you must convert into P12 format. Instructions on how to do this are provided in the Adobe AIR documentation on signing AIR applications.

Store the P12 (.p12) file on your computer; you will need to use it with Flash Builder later.

Register devices to which you wish to deploy applications during development

You must specify any devices on which you intend to run or debug the application in the provisioning profile used to package the application; as such, you must register the devices on the iOS Provisioning Portal.

To register a device you need its Unique Device Identifier (UDID). To get this, connect your device to your computer and launch iTunes. In iTunes, select your device in the Devices section and navigate to the Summary tab. Click the Serial Number label to reveal the Identifier field and the 40 character UDID. Press Command/CTRL+C to copy the UDID to your clipboard.

Define an App ID for the application you are developing

Each application that you wish to deploy must have an App ID, which comprises a Bundle Seed ID (also called the App ID Prefix) and a Bundle Identifier (also called the App ID Suffix). Follow the guide on the iOS Provisioning Portal to create your

App ID.
Note that the Bundle Identifier must be the same as the value of the <id> attribute in your application’s app.xml descriptor file. For example, if you create a Bundle Identifier as “com.adobe. myApp”, then your app.xml file must contain the following:

<!-- A universally unique application identifier. Must be unique across all AIR applications. Using a reverse DNSstyle name as the id is recommended. Required. --> <id>com.adobe.myApp</id> You can use a wildcard in the Bundle Identifier to create a provisioning profile that is valid for a number of applications; for example a provisioning profile with a Bundle Identifier specified as “com.adobe.*” can be used with applications with an id of “com.adobe.myApp” and “com.adobe.myOtherApp”. Also note that once created, you cannot remove an App ID from the iOS Provisioning Portal.

Create a development provisioning profile

The final step you need to complete using the iOS Provisioning Portal is to create an iOS Development Provisioning Profile. You will define a profile name, specify the certificate you created, select an App ID, and choose the device or devices the application can be deployed to. More information on creating a Provisioning Profile can be found in the guide on Apple’s site. Download the provisioning file to your computer; you will need to use it with Flash Builder later.

Specify build packaging information for the project in Flash Builder

Before you are ready to deploy an application to an Apple iOS device you need to specify the information required to package the application as an IPA file.

In the Package Explorer view in Flash Builder, right-click your project and select Properties. In the Properties dialog box, select ActionScript Build Packaging > Apple iOS (for an ActionScript project) or Flex Build Packaging > Apple iOS (for a Flex project). In the Digital Signature tab, specify the previously saved P12 certificate file and the provisioning file for your project. Click Apply and then click OK.

When you want to create an IPA file simply right-click the project name in the Package Explorer view and select Export > Flash Builder > Release build. Follow the steps in the wizard to create your IPA file.

CONCLUSIONS

If you want to learn more about mobile development for Android, iOS, and PlayBook using Adobe AIR, Flash Builder, and Flex I encourage you to check these resources:

  • Adobe Mobile and Devices Development Center
  • Creating Flex Mobile Apps with Flash Builder for PHP tutorial
  • Great list of resources for designing and skinning mobile applications

About The Authors

Mihai Corlan

Mihai Corlan is a world wide developer evangelist at Adobe focusing on Flex, AIR, Flash Builder, and Flex, and HTML. Before that he worked with Flex Builder as a computer scientist. Prior to joining Adobe, Mihai was a senior web developer with InterAKT Online (acquired by Adobe in 2006), where he built web applications, frameworks, desktop software, and RIAs. Since 2008 he’s been writing about RIAs and mobile development at http:// corlan.org

You can follow him on Twitter http://twitter.com/mcorlan

Recommended Book

Continuous Delivery

Adobe Flex: Training from the Source was written by a team of authors with practical experience as consultants, mentors and developers of courseware, this book/CD uses project-based tutorials, and is designed to teach beginning Flex developers the details of building and architecting real-world rich internet applications using Flash Builder incorporating MXML and ActionScript 3.0.Flex 4.5 features, such as new enhancements to the Spark architecture and component set. It will also show you how to take advantage of the improvements to core Flex infrastructure for large application development.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Flash Builder 4.5 for PHP

Adobe/Zend Tools for the PHP Professional

By Marco Tabini

3,231 Downloads · Refcard 96 of 151 (see them all)

Download
FREE PDF


The Essential Flash Builder 4.5 for PHP: Adobe/Zend Tools for the PHP Professional Cheat Sheet

"Flash Builder 4.5 for PHP, Adobe/Zend Tools for the PHP Professional is a DZone Refcard that covers tools used by professional web developers to develop applications with slick, Flex UIs and powerful, battle-tested backends coded in PHP. Adobes new Eclipse-based IDE, Flash Builder 4.5 for PHP, was co-developed by Adobe and Zend Technologies. Its one of the more interesting cross-platform integrations in a long time. This Refcard will show you how to profit from this marriage of tools created by the leaders in the RIA and PHP development arenas."
HTML Preview
Getting Started With Integrating PHP and Flex

Adobe® Flash® BuilderTM 4.5 for PHP: Adobe/Zend Tools for the PHP Professional

By Marco Tabini

WHAT IS FLEX?

Flex is an open-source framework developed and distributed by Adobe Systems. It is based on the Adobe® Flash Platform and primarily provides a streamlined approach to the development of Rich Internet Applications.

Flex eliminates many of the designer-oriented features of Flash in favor of establishing a development environment that caters more to programmers. As such, you will find that Flex encompasses many of the concepts that you are already familiar with if you have developed front-end systems using JavaScript or, indeed, most other GUI programming environment, allowing you to take advantage of the underlying Flash infrastructure without having to worry about concepts like timelines, assets, and so on.

Flex is multi-platform—this means that, with some exceptions, you can run a Flex application on any platform that supports Adobe Flash Player. If your users run on Windows, OS X or Linux and their browsers have a recent version of the Flash Player plug-in installed, they will also be able to run your Flex applications without a problem.

Because Flex is open source, there is no cost associated with creating and distribution applications that are based on it.

Hot Tip

You can download Adobe Flex SDK for free directly from the Adobe website at http://www.adobe.com/products/flex/

What is Adobe AIR?

The Adobe Integrated Runtime (Adobe AIR) is a companion technology to the Flex framework that extends the functionality provided by the latter into desktop application development. With AIR, you can build Flex applications that can be deployed as native applications on your user's machines, thus gaining all the advantages of running in a desktop environment.

Like Flex, AIR is also cross-platform, which means that you can write your code once and immediately deploy it across multiple operating systems. Because they run natively rather than in a web browser, AIR applications also gain access to functionality that is usually restricted by the Flash Player's security model, such as local file manipulation, unrestricted access to the network, and so forth.

What is Adobe Flash Builder?

Flash Builder 4 is Adobe's IDE for developing Flex and AIR applications. Although Flash Builder 4 is not required in order to compile or run a Flex-based application, it significantly simplifies the process of Flex development by providing an integrated environment that includes code intelligence, real-time analysis, compilation support, live debugging and much more.

Flash Builder 4 is based on the open-source Eclipse IDE and can either be downloaded as a standalone product or as a plug-in for the latter. Like Eclipse, Flash Builder 4 is also crossplatform and runs on both Windows and OS X.

Hot Tip

You can download a 60-day trial of Flash Builder 4 from the Adobe website at http://www.adobe.com/products/flex/

BUILDING APPLICATIONS WITH FLASH® BUILDER™ 4 AND PHP

Even though Flex is based on Flash, you don’t need to be proficient in the latter in order to use the former.

Flex uses a language called ActionScript3 (AS3), which is itself derived from the ECMAScript standard. ECMAScript is the same basic definition on which JavaScript is based—therefore, if you have any familiarity with browser programming, it's likely that you will find your bearings in AS3 very quickly.

Flex applications are based on the concept of component. A component defines a container of behaviors and, optionally, of a user interface representation. Components can be visual or non-visual, depending on whether the provide an interface of some kind (like a button) or just functionality of some kind (like a library for connecting to a remote server).

The visual structure of a component can be easily defined using MXML, Adobe’s specialized brand of XML. Other than the use of specific namespaces, MXML is nothing more than well-formed XML code; by nesting multiple components, you can create complex GUIs without ever writing a line of code.

Creating Flex Applications

Flash® Builder 4 makes creating new applications as easy as following the steps of its New Application Wizard. Simple select New Flex® Project from the File menu, then choose a name and type for your application. If you intend to write code that will be executed inside a browser, choose "Web" for your application type; if, on the other hand, you want to build a desktop application, choose "Desktop" instead.

You newly-created Flex project will contain a component that represents the application's main entry point:


<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Declarations>
</fx:Declarations>
</s:Application>

From here on, you can add more components to your application simply by typing the MXML code that represents them in the appropriate order. However, Flash Builder 4's strength resides in its visual layout editor, which allows you to arrange and wire the different components that make up your user interface using a WYSIWYG approach. For example, you can add a DataGrid object to show the contents of a data structure and then a button to fetch the data–all enclosed in a VGroup object to provide the overall layout:

Flex’s powerful layout capabilities, like the rest of the framework, are also designed to be developer-friendly and are almost entirely based on standard CSS, with a few exceptions designed to make automated positioning easier.

Useful Flex Components

Flex provides a rich ecosystem of components that can be easily expanded to meet your needs. While many of its components are designed to closely mimic their HTML cousins, there are also a number that provide unique functionality. For example:

  • AdvancedDataGrid and DataGrid: display tabular data in a rich, editable environment.
  • DateChooser and DateField: simplify the process of choosing and formatting date values.
  • NumericStepper: allows the user to increment and decrement a numeric value.
  • RichEditableText: allows you to create a rich text editor with support for several formatting options (e.g.: italic, bold, etc.).
  • VideoDisplay/VideoPlayer: provide fully-featured and completely skinnable video players that can be embedded directly in your application.
  • HSlider/VSliders:allows the user to select a value by sliding a selector across a horizontal or vertical range.
  • HGroup/VGroup: automatically arrange their content horizontally or vertically. Combine to easily create complex layouts.
  • Accordion/TabNavigator: allow multiple content panels to stack and be displayed one at a time.
  • MenuBar/TabBar: add a menu or tab bar to your component.
  • Flex Charting: adds powerful charting abilities to your applications.

Hot Tip

While Flex Charting and AdvancedDataGrid were only available in the Professional version of Flex Builder 3, they are now included in all versions of Flash Builder 4.

Connecting to PHP with AMF Introspection

One of the most interesting features of Flex is that it is designed to provide powerful data connectivity capabilities in a variety of formats and protocols, including XML, SOAP, JSON and Adobe’s own AMF. In fact, in most cases you will be able to use Flash Builder 4 to connect your Flex application to a PHP backend without having to write a single line of code in either!

In order to use Flash Builder 4's PHP-aware functionality through AMF, you need to have direct access to the root directory of a copy of your site—either through a network share or on your local computer. To get started, select Connect to Data/Service… from the Data menu, then choose PHP from the list of available connectors. Flash Builder 4 will ask you to confirm that your project type is set to PHP, then specify both the location of your site's server root and its URL:

At this point, you can click "Validate Configuration" to make Flash Builder 4 run a simple test to determine whether it can access your site as expected, then OK to complete the set up process.

Now, Flash Builder 4 will ask you to choose a PHP class that will provide the entry point to which your Flex application will connect. If your code is not encapsulated in classes, you could create some simple stubs for the purpose of providing services to your Flash Builder 4 code. The wizard will automatically fill in the defaults for you based on the name of the PHP file that you select.

Hot Tip

In order for this system to work, it is important that the class you want to import be stored in a file of the same name [e.g.: Index inside index.php]. Otherwise, Zend_AMF will be unable to find it.

At this point, if you website does not include a copy of Zend_AMF, a Zend Framework module that Flash Builder 4 uses to marshal data, remote procedure calls and error management, you will be asked to download and install a copy. This is required because Flash Builder 4 makes use of Action Message Format (AMF), a protocol that PHP does not support by default.

Hot Tip

Your application does not need to use Zend Framework in order to take advantage of AMF—Flash Builder 4 will only use Zend_AMF in order to communicate with your server, independently of the rest of your code.

Flash Builder 4 will introspect your code and discover which methods the service makes available:

Once you click Finish, the wizard will create a series of classes inside your project that provide all the necessary functionality required to connect to your project and execute your web service.

Hot Tip

Remember that it is your responsibility to provide a security layer where required—for example, by passing a secure key to the service as appropriate.

Establishing Data Connections

Your application is now capable of connecting to the PHP backend, but the data that the latter provides is not yet wired to any of the controls.

Luckily, this, too, is something that can be done without writing a line of code. You can, instead, use the Data/Services panel, visible in the bottom tray of the Flash Builder 4 window, where all the remote data services defined in your application are visible:

All you need to do in order to connect the data returned by a service call to any of your components is to simply drag it from the Data/Services panel to the component. Flash Builder 4 will ask you whether you intend to create a new call, or use an existing one. In the former case, you will first need to specify the type of data returned by the remote service call, because the data connection wizard has no way of determining it by means of static analysis of your code.

Flash Builder 4 can, however, auto-detect the data type returned by a service call by making a call to it, or you can specify it by hand. Where a sample service call will have no adverse effects on your PHP backend, allowing the wizard to determine the return type automatically is usually sufficient and produces all the infrastructure required to handle the data on the Flex side.

Hot Tip

In order for your data to be used in a Flex application, it must conform to all the appropriate AS3 rules—for example, you cannont return objects with properties whose names are reserved AS3 keywords like protected or private, even if those are perfectly acceptable in PHP

Your Flex application now has access to all the data returned by your service. If, for example, you drag a service on to a DataGrid component, the latter will be automatically populated with all the appropriate data columns—all you need to do is remove those you don’t want displayed and rename the header of the others to the proper human-readable format:

Your application is now fully functional—if you execute it, you will see that the data service is automatically called as soon as the DataGrid object finishes loading. If the call is successful, the data is immediately loaded and displayed.

If you prefer to add a manual method of refreshing the information, you can simply drag the appropriate data call on to the button—this will create all the code needed so that, when the user clicks on it at runtime, the service will be called again and all the data automatically updated.

Differences between PHP and AS3 Data

While much of the data types are interchangeable between AS3 and PHP, there are some notable differences.

  • Integer values in PHP can either be 32- or 64-bit long, whereas, in AS3, they are always 64 bits. Therefore, you must be prepared for the fact that a numeric value passed from AS3 to PHP may be represented as a float even if it is, in fact, just a large integer.

  • String values in AS3 are always Unicode-compliant. It is up to you to ensure Unicode compliance on the PHP side.

  • Array values in AS3 can only have contiguous numeric keys starting at zero. If your PHP arrays have string keys or non-contiguous numeric keys, they will be represented as objects in AS3.

    You should avoid passing objects into AS3 that contain members whose keys are reserved keywords, as handling them will be inconvenient—and many of Flash Builder 4's facilities will refuse to work with them.

Under most circumstances, these issues are unlikely to affect your application because both AS3 and PHP have a significant amount of flexibility.

CONNECTING TO WEB SERVICES

SOAP

AMF is not your only choice when it comes to external connectivity from Flash Builder 4—almost exactly the same functionality can just as easily be used to connect to an XML web service powered by SOAP.

You can start the process by selecting Connect To Data/ Service… from the Data menu and then choosing WSDL as the service type. This will bring up a dialog box that asks you to provide the URL of the service's WSDL specification:

Like before, Flash Builder 4 will fetch the WSDL file from the server and introspect it, extracting all the available remote procedure calls. You will then be able to drag and drop the data into your application like before.

Accessing XML Services

Of course, SOAP is not the only way of retrieving XML data from a remote location. Flash Builder 4 provides facilities for introspecting a remote URL that simply returns a flat XML document and extracting information from it.

Once again, you will need to click on Connect To Data/ Service… from the Data menu and, this time, choose XML as the service type. Flash Builder 4 will ask you to provide the URL of the service you wish to access, invoke it and create a stub class in AS3 to encapsulate the data:

The resulting data provider will become available in the Data/ Services panel of Flash Builder 4's GUI, from where you can connect it to your components like before.

Hot Tip

Be mindful of the fact that, when manipulation raw XML, Flash Builder 4 has no way of determining whether your service provides data in a consistent format. Therefore, you should ensure that this is the case, or your service call may unexpectedly fail at runtime.

JSON and XML

JSON (JavaScript Object Notation) has rapidly become a very popular choice for web service development because of its simplicity, lightweight format and ease of use in a number of languages.

While PHP has had built-in support for JSON since version 5.2.0, AS3 does not have any facilities for manipulating JSON data. Luckily, Flex provides a number of different ways for using JSON.

To start, you will need a PHP script that takes zero or more parameters either through a GET or POST HTTP transaction and outputs JSON-formatted data. For example:


<?php
function getTimeline($user) {
	$data = json_decode(
		file_get_contents("
			http://api.twitter.com/1/statuses/user_timeline.
			json?screen_name=" . urlencode($user)));
	
	foreach($data as $v) {
		unset($v->user->protected);
	}
	return $data;
}
echo json_encode(getTimeline($_GET['user']));

The simplest way of connecting to this service consists of once again using the Data/Service Connector wizard to access arbitrary HTTP-based web services. Choosing "HTTP" from the Connect To Data/Service… menu will result in this dialog, where Flash Builder 4 asks for the URL of the service and its parameters:

Once you provide the correct information and click on Finish, the wizard will once again create all the infrastructure required to run your service and make it available as before. The HTTP Data/Service Connection wizard also supports XML data.

DEPLOYING YOUR APPLICATION

In most cases, you will want to develop your application in Debug mode. This causes the Flex compiler to add all sorts of useful information that can be used to debugger to help you address any issues that may occur within your application.

However, when it comes time to deploy your application for production, you will want to switch to a Release build so that you can end up with the most compact and efficient codebase possible. You can do so by selecting Export Release Build... from the Build menu.

Exporting a Release build causes a new directory, called binrelease, which contains a number of different files:

Most of these files play a support role to your application—in fact, the only one you will normally interact with is the host HTML file that contains the code required to display your application.

Hot Tip

You can change the template used to generate your host HTML file by editing the html-template/index.template. html file in your application's root directory.

Passing Data to Your Flex Application

It is sometimes useful to pass data, like request parameters, to your Flex application as it is being initialized on the client browser.

This can be accomplished by introducing a special parameter in the HTML code that causes the application to be embedded in the web page. In reality, Flex provides a series of convenient wrappers that make the job even easier; if you look inside your HTML template, you will find a portion of code that looks like:


var flashvars = {};
...
swfobject.embedSWF(
		"Fle.swf", "flashContent",
		"100%", "100%",
		swfVersionStr, xiSwfUrlStr,
		flashvars, params, attributes);

All you need to do is change the content of flashVars to suit your need—that same data will be made available inside the application as the FlexGlobals.topLevelApplication.parameters object, where you can peruse it as needed.

Understanding the Security Model for Flash

When running in the browser, Flash employs a very strict security model that places your code in a sandbox through which all network and disk activities are regulated.

Hot Tip

For more information about the Flash security model, read the "Security" section under "Application architecture" in the Flash Builder help online at http//help.adobe.com/en_US/Flex/4.0/UsingSDK/

The sandbox is turned off during debugging—therefore, you don't normally become aware of it until you run your code in production mode and find out that your application cannot access any of its remote data.

Flash supports a number of different sandboxes, depending on what kind of data your application needs to deal with. Most of the time, you will want to use the local-with-networking sandbox, which allows your application to access remote locations, but denies all access to local files.

By default, the sandbox model prevents an application from accessing any resources outside of its own domain, unless that domain specifically grants access with a crossdomain.xml file. Therefore, it is important to remember that you may not be able to access information across different domains.

Hot Tip

Adobe AIR applications usually run in the local-trusted sandbox and, therefore, are not subject to connectivity restrictions.

Documenting Your Code with ASDoc

While much of the functionality provided by Flex can be accessed without writing significant amounts of AS3 code, it is entirely possible to address extremely complex tasks entirely within the Flex runtime — systems as complex as encryption engines and image compression libraries have been built in pure AS3 and are used in production every day (in fact, the entire Flex framework itself is built in AS3 as well).

Through a featured called ASDoc, Flash Builder 4 allows you to write inline comments that can be used to document your entire codebase. The syntax used by ASDoc is very similar to the PHPDoc syntax that is commonly used to comment PHP code; for example:


/**
* Performs some important function
*
* @param event The event dispatched to this method
*/
protected function handler(event:FlexEvent):void
{
	// Do something
}

Flash Builder 4 will automatically scan your code and add any information you write as part of your ASDoc blocks to its code intelligence features; these, in turn, will display the information as you use your code, providing you with a handy dynamic reference for your classes and methods:

About The Author

Marco Tabini

Marco Tabini is the co-founder, with Arbi Arzoumani, of php|architect, the world's largest PHP magazine in the English language, currently distributed in over 145 countries. He is also the co-founder, with Keith Casey, of Blue Parabola, LLC, a consulting firm that specializes in information architecture, code and security auditing, large-scale deployments and optimization.

An accomplished author on the subject of PHP and the business of web development, Marco is also a frequent speaker at PHP and OSS conferences throughout the world.

Recommended Book

Flash Builder 4 and Flex 4

Create desktop applications that behave identically on Windows, Mac OS X, and Linux with Adobe's new Flash Builder 4 platform and this in-depth guide. The book's tutorials and explanations walk you step-by-step through Flash Builder’s new, faster tools; the new framework for generating code; how to connect to popular application servers; upgrading from Flex 3; and much more.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose: Google, Microsoft, and Yahoo Team Up to Improve Search

Google, Microsoft, and Yahoo are usually thought of as competitors in the web search market, but that changed today with a collaboration between the three companies. The companies launched Schema.org, a website with common HTML tags that webmasters can use to...

1 replies - 17325 views - 06/02/11 by Ross Jernigan in Daily Dose

Scripps Networks finds a fit Case Study

0 replies - 3123 views - 05/18/11 by Brandon Nokes in Whitepapers