ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


Introduction to Flex Using PHP

by Jack Herrington
07/19/2007

Getting Started with PHP and Flex

With all the hype (and money) surrounding buzzword terms like Web 2.0 and Rich Internet Applications (RIA), it's easy to wonder, "How can I integrate that into my PHP application?" Certainly, Asynchronous JavaScript and XML (Ajax) technologies that use JavaScript code are a good option. But you should also have a look at the Adobe Flex framework. With Flex, you can quickly build functional, attractive user interfaces in Adobe Flash that communicate to your PHP web application through XML.

Let's step back and look at what Flex is and how it compares to standard HTML development with a language like PHP. Both the traditional Web 1.0 HTML architecture and the Flex-based architecture are shown in Figure 1.

The Flex architecture compared to the standard PHP web page architecture
Figure 1. The Flex architecture compared to the standard PHP web page architecture

On the left, you can see the standard PHP workflow you've come to know. The browser makes a request of the PHP web page, which talks to the database and sends back HTML to satisfy the customer's request.

On the right is the Flex approach. The customer navigates to the page, where a Flex application (a SWF file) is loaded that contains the user interface for the form. This Flex application then uses XML to read or write data to the PHP pages on the server. Those new PHP pages talk to the database and return XML to the Flex application for display. The dashed lines on the list.html and list.swf files indicate that they were generated by Adobe Flex Builder 2.

The advantage of Flex is that the framework provides an amazing set of interface tools that make it easy to build highly interactive user interfaces. In addition, there are many advantages to having the PHP pages return XML instead of (or in addition to) HTML. Here are just a few:

Flex Builder 2 builds the Flex applications. Figure 2 shows how Flex Builder 2 takes the MXML and ActionScript files that define the interface and generates the application's SWF file and the host HTML pages.

The Flex Builder 2 compilation cycle
Figure 2. The Flex Builder 2 compilation cycle

In Flex Builder, you edit the list.mxml file. When you click Run to test the page, Flex Builder compiles the list.mxml file into an SWF file and builds a page that references that file. You can test the file locally on your machine and, when it's ready, push the HTML and SWF files up to your web pages to get them into production. Flex Builder even has a fully integrated debugger that you can use to step through the ActionScript code that runs in the Flex application.

The rest of this article walks you through installing Flex Builder 2, creating a Flex project, and attaching it to a simple PHP web application.

Installing Flex Builder 2

Flex Builder 2 is available as a free trial download from Adobe. It runs on both Microsoft Windows and Mac OS X and has a simple installer on both platforms that gets you up and running quickly. You have two download options: the standalone version and an Eclipse plug-in. When in doubt, choose the standalone version.

Flex Builder 2 is based on the Eclipse integrated development environment (IDE) framework. If you are familiar with Eclipse or you are using it already, you might want to download Flex Builder as a plug-in and simply add it to your existing Eclipse installation. I mention this because there are a couple of good IDEs for PHP that are also based on Eclipse. One is PHPEclipse, another is Eclipse's own PHP Development Tools project. So, having both the PHP IDE and the Flex Builder 2 plug-ins installed gives you a single IDE to work on your user interface and your backend PHP code. (In addition to the Flex Builder 2 download, have a look at Adobe's PHP/Flex page.)

After you've installed Flex Builder 2, launch it and create a new project. To do this, select File > New > Flex Project. A dialog box similar to Figure 3 appears.

The first page of the New Flex Project Wizard
Figure 3. The first page of the New Flex Project Wizard

Select the first option, Basic, because you're going to use PHP pages on the server to get to the data. Click Next, which takes you to the final New Project Wizard page (see Figure 4).

The second page of the New Flex Project Wizard
Figure 4. The second page of the New Flex Project Wizard

I've named the project flex_php, but you can use any name you like. By default, the wizard puts the files in your My Documents directory on Windows (your Documents directory on Mac OS X). You can change that location, as well.

Testing Flex Builder 2

Just to make sure that everything is working well, let's do a little "Hello World" test. Thankfully, Flex Builder has already created a starting MXML file in the new Flex Project. So, you can add a simple line of Flex code to the file, as shown in Figure 5.

Creating a simple
Figure 5. Creating a simple "Hello World" Flex application

If you want to copy and paste the code, here it is:

<mx:Label text="Hello World">
</mx:Label>

This code adds a single label element to the Flex application with the text "Hello World." When you click Run in the toolbar, Flex compiles the MXML code and brings up your web browser with the application running. Figure 6 shows the page on a Macintosh.

The
Figure 6. The "Hello World" application

Not too much to look at, but hey, what do you want from a "Hello World" application? At least you now know that everything is installed properly and running smoothly.

You've also seen a bit of MXML. Here is the complete fragment:

<mx:Application xmlns:mx="..." layout="absolute">
<mx:Label text="Hello World">
</mx:Label>
</mx:Application>

The <mx:Application> tag defines the application. Then, the <mx:Label> tag places a label in the layout of the application. The text property defines the string that will appear in the label. A label is just one of the bevy of controls that the Flex framework provides. You also get buttons, sliders, tabs, images, movies, and even charts and graphs.

Flex allows you to script the application by adding ActionScript code blocks either in the MXML file or as external ActionScript files, in much the same way JavaScript code can go in the web page or be externally sourced from a JavaScript file.

Building the Subscriber PHP Application

To build a Flex interface that talks to a PHP application, you first need a PHP application. Say you've decided to build an application that stores a list of subscribers, including their first names, last names, and email addresses. The first step in building the application is to figure out where to store the data. You do that in a MySQL database using a table that the MySQL database code shown in Listing 1 created.

Listing 1. db.sql

DROP TABLE IF EXISTS emails;

CREATE TABLE emails (
   first TEXT,
   last TEXT,
   email TEXT
);

To get that table into MySQL, you must first create the database, then run the following db.sql code:

% mysqladmin create flex_php
% mysql flex_php < db.sql

To add some example data, run the following script from the command line:

% mysql flex_php
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 28 to server version: 4.0.17-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> INSERT INTO emails VALUES ('jack','herrington','jack_d_herrington@pobox.com' );
Query OK, 1 row affected (0.07 sec)

mysql> quit

You can use whatever values you like.

Then, create a list.php script that reads the data from the database table and exports it as XML. Listing 2 shows this PHP file.

Listing 2. list.php

<?php
header('Content-Type: text/xml');
?>
<subscribers>
<?php
require_once("DB.php");

$dsn = 'mysql://root@localhost/flex_php';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

$res = $db->query( "SELECT first, last, email FROM emails" );
while( $res->fetchInto( $row ) )
{
?>
<subscriber>
<first><?php echo( $row[0] ); ?></first>
<last><?php echo( $row[1] ); ?></last>
<email><?php echo( $row[2] ); ?></email>
</subscriber>
<?php
}
?>
</subscribers>

First, this script uses the header() function to tell the web server that the return is going to be XML. It then connects to the web server using the DB module available from PEAR (and installed by default with most installations). After the script connects to the database, it runs a simple Structured Query Language (SQL) query to collect all the records, then uses a while loop to write them out as XML tags.

Running the script on the command line produces the following result:

% php list.php
<subscribers>
<subscriber>
<first>jack</first>
<last>herrington</last>
<email>jack_d_herrington@pobox.com</email>
</subscriber>
</subscribers>
%

You now have a script that shows the contents of your database as XML. You can connect that to your Flex application easily. But you also need a way to add records to the database. For that, a separate addform.php script (Listing 3) is required.

Listing 3. addform.php

<?php
header('Content-Type: text/xml');

require_once("DB.php");

$dsn = 'mysql://root@localhost/flex_php';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

$sth = $db->prepare(
  "INSERT INTO emails ( first, last, email ) VALUES ( ?, ?, ? )"
);

$db->execute( $sth,
  array( $_POST['first'], $_POST['last'], $_POST['email'] )
);
?>
<ok />

This simple script first tells the web server that the return type is XML. It then connects to the database, prepares the INSERT statement, and runs it with the variables provided by the POST arguments that will come from the Flex application. Flex applications use POST data just like any other web client, which makes it easy to connect with existing web applications.

That's all you need on the PHP scripts side. Now, you must build the Flex applications for viewing the subscriber list and adding new subscribers. I separate the frontend of the application into two components: a backend Flex application for administrators that views the list of subscribers, and a frontend Flex application that offers a subscription form to the customer.

Building the Subscriber Viewer

To build the backend subscriber viewer, you need to wrap a Flex user interface around the XML list.php page. Creating an attractive data viewer for XML data that comes from PHP couldn't be easier with Flex. Listing 4 shows the list.mxml file.

Listing 4. list.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  <mx:XML id="mydata" source="http://localhost/flex_php/list.php"></mx:XML>

  <mx:DataGrid id="emaillist" x="10" y="10" dataProvider="{mydata..subscriber}">
    <mx:columns> 
      <mx:DataGridColumn dataField="first" /> 
      <mx:DataGridColumn dataField="last" /> 
      <mx:DataGridColumn dataField="email" /> 
    </mx:columns> 
  </mx:DataGrid>
</mx:Application>

The <mx:XML> tag defines the location of XML data source. (That's the list.php file you put together earlier.) The <mx:DataGrid> tag is a Flex control that displays data in a tabular format. To tell the DataGrid control which fields to display, create an <mx:columns> tag that contains <mx:DataGridColumn> tags for each field.

Now, when you click Run, a browser pops up, and you see the subscriber list (See Figure 7).

The Flex list application, which shows the subscribers
Figure 7. The Flex list application, which shows the subscribers

Not only is the data grid attractive, it's also functional. For example, clicking the headings allows you to change the sort ordering without having to add that code to your PHP script or go back to the server for the data. And you can change the order of the columns as you like—again, without going back to the server.

I've done a lot of Ajax and Dynamic HTML (DHTML) work, and I certainly haven't seen a way to display data as quickly or as cleanly as this approach.

Building the Subscriber Add Form

The next step is to build the frontend subscription application that will allow users to register. This form uses the addform.php script on the server to add new entries to the database. The MXML script for the form is shown in Listing 5.

Listing 5. addform.mxml

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  <mx:HTTPService id="srv" url="http://localhost/flex_php/addform.php" method="POST">
    <mx:request>
      <first>{first.text}</first>
      <last>{last.text}</last>
      <email>{email.text}</email>
    </mx:request>
  </mx:HTTPService>

  <mx:Form>
    <mx:FormItem label="First Name">
      <mx:TextInput id="first"/>
    </mx:FormItem>
    <mx:FormItem label="Last Name">
      <mx:TextInput id="last"/>
    </mx:FormItem>
    <mx:FormItem label="Email">
      <mx:TextInput id="email"/>
    </mx:FormItem>
    <mx:FormItem>
      <mx:Button label="Subscribe" click="srv.send()"/>
    </mx:FormItem>
  </mx:Form>
</mx:Application>

At the top of the file is the definition of the HTTP service that the PHP addform.php script provides. At the bottom is the form, with all the labels and text input areas as well as the Subscribe button.

When you click Run, the Flex application shown in Figure 8 appears in the web browser.

The subscriber add form
Figure 8. The subscriber add form

Type a first name, last name, and email address, then click Subscribe. From there, you can go back to the Flex list application and see the new entry (Figure 9).

The list with the new data
Figure 9. The list with the new data

This example doesn't even begin to cover the surface of what you can do with Flex and its user interface toolkit, but it does give you a simple path to connecting your PHP web application to a Flex application in a real way. The final step is to push the HTML and SWF files in your project's bin directory to your web server, which puts your Flex application into production.

Conclusion

Flex isn't the only way to create RIAs; JavaScript and Ajax can also provide your applications with a lot of interactivity. But Flex has many advantages. First, it has a rich cross-platform user interface toolkit that's easier to work with, in some cases, than the DHTML model. Second, it encourages you to architect your PHP application to support HTML and XML interfaces, which is good for everyone.

Flex Builder 2's biggest advantage is its ability to create self-contained SWF files from MXML applications that talk to your web server. This means that you can create small widgets or Flash-based interface enhancements for your site quickly. That's a nice way of getting into Flex without having to move your entire interface over to it. Give it a try; I think you'll be blown away.

Jack Herrington is an engineer, author and presenter who lives and works in the Bay Area. His mission is to expose his fellow engineers to new technologies. That covers a broad spectrum, from demonstrating programs that write other programs in the book Code Generation in Action. Providing techniques for building customer centered web sites in PHP Hacks. All the way writing a how-to on audio blogging called Podcasting Hacks.


Return to ONLamp.com.

Copyright © 2009 O'Reilly Media, Inc.