Prerequisite knowledge

Some knowledge of PHP, Flex, and web applications will be helpful.

User level


New features in Flash Builder 4 makes it easier than ever for PHP developers to connect a Flex application to their PHP servers on the back end. Flex is a great companion to a PHP application. By using Flex and the Flash Platform you can incorporate video, add rich interactive data visualizations such as charts, and take advantage of real-time features that aren't available with HTML.

In Part 1 of this three-part series of tutorials, I'm going to show you how to consume a basic XML document that is generated by PHP and walk you through some of the new data-centric development features that are available in Flash Builder 4.

In Part 2, I'll show you how Flash Builder 4 makes it easier to use Flash Remoting to connect your Flex and PHP application.

In Part 3, I will provide an overview of some of the advanced data features in Flash Builder 4 for implicit paging and data management, which you can use to make your applications more intuitive and more robust.

Flash Builder 4 is Flex Builder 3 with new functionality

If you've been using the Flex framework and PHP for a while you may be confused about this new tool with the same version number as the newest version of Flex. While working on the next generation of Flex Builder, Adobe realized that it was being used for a lot more than just applications with the Flex framework. For example, developers who were creating applications using only ActionScript 3.0 used Flex Builder to edit their ActionScript code.

Adobe also introduced Flash Catalyst, which allows designers to create interactive content from a Photoshop or Illustrator document without writing code. Behind the scenes Flash Catalyst generates Flex code and the projects it creates can be easily opened in the next generation of Flex Builder.

In order to bring the tools under the same brand and acknowledge that not everyone who used Flex builder was building a Flex application, Adobe chose to rename Flex Builder to Flash Builder for the next version. It has all the features of Flex Builder plus all of the new ones added in this version–just with a different name.

Setting up your environment

To follow the steps in this tutorial, you’ll need Flash Builder 4 installed. You’ll also need access to a web server with PHP support and an SQL database. If you don’t already have such an environment configured, you’ll likely want to set up Apache, MySQL, and PHP together. See Setting up a PHP development environment for Dreamweaver or Building your first dynamic website – Part 1: Setting up your site and database connection for help in setting up XAMPP on Windows or MAMP on Mac OS X. For Linux, see Setting up your PHP server environment using Linux, Apache, MySQL, and PHP. While these articles cover Dreamweaver, you do not need Dreamweaver for the purposes of this tutorial, just the Apache, MySQL, and PHP technology stack.

Unpacking the sample files

After downloading and unzipping the sample files for this article, place the create_xml.php file in your web server’s root folder (typically htdocs for Apache). The file uses “root” for both the username and password, so you may need to edit the file if you are using a different username or password for MySQL.

You can use the included php_demos.sql file to create the database and table used in this tutorial. If you’re using MySQL, follow these steps:

  1. From the command line type mysql -u root -p and enter your password when prompted.
  2. To build the database, at the mysql prompt, type SOURCE php_demos.sql; and press Enter.
  3. Type quit and press Enter.

Working with PHP Developers and Zend Studio

Flash Builder 4 supports a seamless workflow with Zend Studio. If you're using the plug-in version of Zend Studio you can just install it right into the standalone version of Flash Builder 4 and have your Flex development and PHP development side by side in the same tool.

Your first Flex/PHP application

I'm going to walk you through how to get started with Flex and PHP by bringing in some XML from a PHP application using some of the data centric development features of Flash Builder 4.

Set up the Flex project

Follow these steps to create a new Flex project:

  1. In Flash Builder 4, choose File > New > Flex Project
  2. Type a name for the project; I used MyFirstFlexPHPApplication.

    When you start a new project you give it a name, specify if you want to create a browser or desktop application, and select the version of the Flex SDK you want to use. You also have the option to select a server type. If you're just consuming an XML document or any other REST API, you don't need to select a server. In Part 2 of this series you'll select PHP, but for this project, just keep None/Other selected.

  3. Leave the other settings as they are (see Figure 1) and click Next.

The next screen allows you to customize the output location of your project, which can be helpful if you're running a local server and you want to test your Flex application in a web server directory without copying the Flex source code files there.

  1. Click Next.

    The final screen allows you to add libraries and link projects, which you don't need for this project.

  2. Click Finish.

Examine the PHP code

One of the most straightforward ways to bring data into a Flex application is with XML. The sample files include create_xml.php, which accesses the database and creates an XML formatted response based on the data. The table I'm using contains data about the National Forest system (see Figure 2).

The PHP code uses PHP5's DOM functionality to build and then render the query data in XML format.



<?php $username = "root"; $password = "root"; ?> <?php $connection = mysql_connect("localhost",$username, $password) or die ("Unable to connect to database."); $db = mysql_select_db("php_demos",$connection) or die ("Unable to select database."); $result = mysql_query("select * from national_forests",$connection) or die ("Unable to complete query."); $doc = new DomDocument('1.0'); $root = $doc->createElement('national_forests'); $root = $doc->appendChild($root); while($row = mysql_fetch_assoc( $result ) ) { $forest = $doc->createElement('forest'); $forest = $root->appendChild($forest); $id = $doc->createAttribute('id'); $id = $forest->appendChild($id); $id_value = $doc->createTextNode($row['id']); $id_value = $id->appendChild($id_value); foreach( $row as $fieldname => $fieldvalue) { if($fieldname != "id") { $child = $doc->createElement($fieldname); $child = $forest->appendChild($child); $value = $doc->createTextNode($fieldvalue); $value = $child->appendChild($value); } } } $xml_data = $doc->saveXML(); echo $xml_data; ?>

The code produces an XML document that looks something like this:

<national_forest> <forest id="16"> <state>WY</state> <area>3400000</area> <established>1908-07-01</established> <closest_city>Big Piney, WY</closest_city> <name>Bridger-Teton National Forest</name> </forest> </national_forest>

Data-centric development

If you're familiar with Flex 3 and you’ve worked with XML, then you may know that you'd be able to use an HTTPService class to take the data and bind it to a DataGrid component pretty easily. That approach, however, creates some unfortunate dependencies. If your XML data model has to change then you'll need to go through your entire user interface and change it to reflect the new XML data model.

With data-centric development, in contrast, it's easy to keep the user interface completely separate from the data model. The data-centric development tools use higher level objects and collections that are then bound to the user interface. If your model changes, you only need to change those objects—the UI elements that use them will automatically be updated.

Follow the steps to see how it works:

  1. In Flash Builder 4 select the Data/Services panel near the bottom of the screen or choose Window > Data/Services.
  2. Click Connect to Data/Service to start the Data Services wizard, which supports multiple service types.
  3. Select HTTP (see Figure 3) and click Next.

    I will talk cover the PHP option in Part 2. You'll also see an XML option, which provides an easy, quick way to connect XML data. The XML option is a subset of the HTTP option. Selecting HTTP lets you connect to any HTTP REST service on the web whether it's using JSON, XML, or some other format. It provides a good overview of how the new data-centric development wizards work, so it’s the best choice for an introductory tutorial.

  1. After making sure the create_xml.php file, which generates the XML, is in a web-accessible location (either on a local web server or somewhere on the Internet), type the URL of that file in the URL column under Operations.
  2. Rename the operation to getForests instead of Operation1, and leave the method as GET.

    If you were dealing with a service that required parameters you could use the Parameters options to set them. This is helpful if you are dealing with more complex APIs.

  3. For the Service Name, type ForestsService; a default package name is automatically supplied for you (see Figure 4).
  4. Click Finish.

Flash Builder 4 will generate all of the ActionScript code you need to connect to the server and grab the data. Using Flash Builder 4 you can take it one step further and define the data type that your Flex application will use to represent the data. By specifying the data types you will define the data model in one part of your application and make it independent from the user interface you’re about to build.

To define a data type, follow these steps:

  1. In the Data/Services panel, right-click the getForests() method and select Configure Return Type.
  2. In the Configure Return Type dialog box, you can specify whether you want to use an existing data type or call the service and define the data type with live data. Select Auto-detect The Return Type From Sample Data (see Figure 5) and click Next.

You have three options for auto-detecting the return type in Flash Builder 4. You can provide specific parameters to a service and call it, enter a complete URL with the parameters added on, or enter a sample response to define the data set.

  1. For this basic example there are no parameters so you can just leave the first option selected (see Figure 6) and click Next.

After Flash Builder 4 calls the service it will inspect the XML result and try to figure out what the properties are. You can use select a root to define exactly which part of the XML you want to use as the data type. You can also go through and specify the types for the individual properties.

  1. In this case, select forest as the root so you get back an array of forests.
  2. Next change the properties to their correct data types. Specifically, change the id type to int, area to Number, and established to Date. (see Figure 7).
  3. When you're done, click Finish to generate the code for the data type definition.

Building the user interface

Now you're ready to start building the application’s user interface. With the data-centric development wizards you have created a data model that is easily adjustable if your XML response changes. No UI controls are dependent on it right now and the ones you're about to generate are going to use the model code you created to help them define the UI instead of being based directly on the XML data.

Display the data

To start creating the UI:

  1. Switch to Design view.
  2. Drag a DataGrid from the Components panel to the main area of the screen.
  3. Drag the getForests() operation from the Data/Services panel to your DataGrid.
  4. You'll be presented with a dialog box where you can define the service to use (see Figure 8). You can either create a new service or use an existing one. In this case, you've already defined the ForestsService and the operation so just click OK.

Update the data in a form

Now you've generated the code to call that XML page and the DataGrid has changed to represent the data from your model. The last step is to create an option to modify the data. Flash Builder 4 lets you quickly create a master-detail form to do just that.

  1. Right-click the DataGrid and select Generate Details Form.
  2. In the Generate Form dialog box, you can define which service calls to use, what kind of form to generate, and whether or not to make it editable. Since you've already defined the service call and the return type, simply accept the defaults and click Finish.
  1. Click the master-detail form that Flash Builder 4 created and drag it below the DataGrid (see Figure 10).
  1. Choose File > Save to save your changes.
  2. Choose Run > Run MyFirstFlexPHPApplication to run the application.

You'll see the XML data load and populate the DataGrid. Any data you select in the DataGrid will appear in the form below and you can even make changes to it by editing the data in the form and clicking Submit. That won't change the data in your database (more on that in Part 3) but it will change it within your Flex application. With the data-centric development features in Flash Builder 4 any UI element that depends on that data will be updated because you're changing the underlying model.

Where to go from here

Part 1 focused on Flash Builder 4 data-centric development features. In Part 2 I'll walk you through using a Zend AMF connection, and in Part 3 you’ll use that connection to create a CRUD (Create, Read, Update, and Delete) application so you can modify the data in the database from a Flex application.