Prerequisite knowledge
To follow all the steps in this tutorial you will need general familiarity with Flex and ActionScript 3 as well as PHP. Some knowledge of the PayPal Express Checkout API will also be helpful.
 
User level
Intermediate
Required products
Flash Builder (Download trial)
Sample files
Flex_php.fxp (19 KB)

 
Additional Requirements

 
Flash Builder 4 Eclipse Plug-in
Zend Studio 7.1 for Eclipse
Zend Framework 1.9 or newer
Zend Studio Browser Toolbars
Web server with support for PHP 5 or newer
MySQL server 5 or newer
Sample files:
Developers who work with Flex and PHP can boost their productivity by combining two tools: Flash Builder and Zend Studio for Eclipse. This setup lets you create a combined project with Flex and PHP natures and reap the benefit of coding in both languages. (In Eclipse, natures link a project with specific builders and other settings.) The setup also enables you to debug your Flex and PHP code at the same time.
 
In this article I will show you how to install Flash Builder 4 together with Zend Studio for Eclipse, how to create a combined project, and how to debug a project that uses Zend AMF to send data between Flex and PHP.

 
Installing Flash Builder and Zend Studio for Eclipse together

Flash Builder is delivered in two flavors: one is the standalone version and one is a plug-in version for Eclipse. Because I want to be able to use the same IDE for editing both PHP and Flex code in the same project, I need to have Eclipse with both Zend Studio and Flash Builder installed.
 
The easy way to do this is to install the Zend Studio for Eclipse first, and then start the Flash Builder Eclipse Plug-in installer. Make sure you install in the Zend Studio Toolbar (this will help you to debug the PHP code). This approach should work just fine on Windows. On a Mac you should install first the Flash Builder 4 and then use the update site for Zend Studio 7.1 to add Zend Studio to Flash Builder 4. This is because Flash Builder 4 is Carbon based while Zend Studio is Cocoa.
 
At some point, the Flash Builder 3 installer will ask you for the location of the Eclipse installation folder to which you want to add Flex Builder (see Figure 1).
 
After the installation is done, you are ready to use these tools on Flex and PHP projects.
 
Figure 1. Selecting the Zend Studio installation folder.
Figure 1. Selecting the Zend Studio installation folder.
If the installation was succesful, then you should see something like this:
 
Figure 2. Zend Studio and Flash Builder installed together on Windows.
Figure 2. Zend Studio and Flash Builder installed together on Windows.

 
Creating a Flex and PHP project

Now you are ready to create a project in Zend Studio that can be used for both Flex and PHP code. My prefered workflow when working with Flex and PHP projects is to hava single project for both PHP and Flex because usually I work on both client and server side. However this is not necessary the best workflow, it is more about a personal choice. Some people prefer to create two different projects: one for PHP files and another one for the Flex application.
 
Flash Builder has a Flex project type named PHP. If you create this type of project, it will have only a Flex nature and not a PHP nature, thus some PHP features provided by the Zend Studio will not be available for your project.
 
To have both natures, first create your PHP project. Choose File > New > Other (see Figure 3). In the wizard select PHP > PHP project (see Figure 3) and then click Next. When the PHP Project wizard opens, specify a project name (in this example I used flex_project). Click Finish (see Figure 4).
 
Figure 3. Opening the New Project Wizard.
Figure 3. Opening the New Project Wizard.
Figure 4. Choosing the PHP Project type.
Figure 4. Choosing the PHP Project type.
Figure 5. The PHP project wizard.
Figure 5. The PHP project wizard.
Once you have created the project, right-click on it and choose Add/Change Project Type > Add Flex Project Type… (see Figure 6). This wizard will add Flex nature to your PHP project, so you will be able to create Flex applications and compile them as you would in any Flex project.
 
Figure 6. Adding the Flex Project Nature.
Figure 6. Adding the Flex Project Nature.
Clicking Add Flex Project Nature starts a wizard that looks very similar to the new Flex Project Wizard. Select PHP as the Application server type and then click Next (see Figure 7).
 
Figure 7. The first page of the Add Flex nature wizard.
Figure 7. The first page of the Add Flex nature wizard.
On the second page of the wizard (see Figure 8), enter the path to your web root folder and the URL for this path. For example, on my machine these are /Applications/MAMP/htdocs and http://localhost.
 
Figure 8. The final page of the Add Flex nature wizard.
Figure 8. The final page of the Add Flex nature wizard.
You could also use a network path or a folder that is under your web server root. For example, maybe you have a folder named tests under your root server. In this case the values will be c:\htdocs\tests and http://localhost/tests. After you enter these values, click Validate Configuration. If your server has not started, or if you mispelled the URL or the web root location, you will see a warning. Click Finish when you are done. You should now have a project like the one shown in Figure 9.
 
Figure 9. The combined Flex and PHP project.
Figure 9. The combined Flex and PHP project.
A few notes on these last steps:
  • If you want to create an AIR – PHP project, you need a different approach that involves some additional work. The reason is that the Add/Change Project Type wizard doesn’t support AIR projects; it supports only Flex, Flex Library, ActionScript, and Flash Professional projects. But if you work a little bit, you can do it yourself. For this, first you create the AIR project you want. Then create a PHP project. Eclipse uses a special file, named .project, inside each project to track the natures of the project. Copy the nature and build command nodes from the PHP .project file to the AIR .project file and you are done.
  • Why choose PHP for the application server type in the Add Flex Nature wizard? As you remember the wizard asks for the location and URL of the web server. Flex Builder uses this information to place the compiled Flex application under the path you provided and to launch it from there using the URL you provided. Basically it streamlines the deployment tasks, so you don’t need to manually copy the SWF files, open the browser, or remember the correct URL.
  • After you run the Add/Change Project Type wizard you might see an error in the Problems view stating that “Can not create HTML wrappers…”.You can fix this very easily, just right-click on it and choose Recreate option.

 
Building a Flex and PHP application

Now that you have the project properly set up, you can create a small Flex application that talks with a PHP script using Zend AMF. Zend AMF enables Flex developers to make remote procedure calls from Flex to a PHP class; it is part of the Zend Framework, an open source project.
 
Create the PHP code
Zend AMF lets you to call methods on PHP classes from your Flex application, but the PHP classes must be inside the server web root.
 
As you write this PHP code, it would be nice to be able to use Zend Studio for this. The problem is that your project files are not inside of your server root folder (thus if you create the PHP class in the web server root folder, you will not see it in your Flex PHP project). Fortunately there is a simple solution. Eclipse lets you to link an external folder to any project you might have. Create a folder called zendamf_remote inside your web server root. Make sure that you are in the Flex perspective. Right-click on your project name and choose New > Other, select Folder in the wizard, and then click Next. When the new wizard starts, click Advanced and browse for the web server root folder and select the zendamf_remote folder (see Figure 10). Click Finish and you should now see a new folder named zendamf_remote inside your project.
Figure 10. Creating a linked resource.
Figure 10. Creating a linked resource.
Next, select the PHP perspective in Eclipse (see Figure 11), then rightclick on the zendamf_remote folder and select New > Other….
 
Figure 11. Selecting the PHP perspective.
Figure 11. Selecting the PHP perspective.
When the New wizard opens, select the Class entry from the PHP node and click Next. In the new wizard just type in a file name (MyService.php) and a class name (MyService) and then click Finish (see Figure 12). Repeat this step to create another class called VOAuthor.
 
First let's add a table with some data to your MySQL database server. You can use this code:
 
CREATE TABLE `authors_aut` ( `id_aut` int(11) NOT NULL auto_increment, `fname_aut` varchar(255) NOT NULL, `lname_aut` varchar(255) default NULL, PRIMARY KEY (`id_aut`), UNIQUE KEY `fname_aut` (`fname_aut`,`lname_aut`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; INSERT INTO `authors_aut` VALUES (1, 'Dantes', 'Alighierie'); INSERT INTO `authors_aut` VALUES (2, 'William', 'Shakespeare'); INSERT INTO `authors_aut` VALUES (3, 'Umberto', 'Eco'); INSERT INTO `authors_aut` VALUES (4, 'Niccolo', 'Machiavelli');
What I want to do is to create the PHP code to retrieve all the records from a table from a MySQL database, and the code for updateing one record from the same table. For this, I create the PHP class MyService wich is the class I will call from Flex. This class provides two methods: getData() and saveData(). Then I create the PHP class VOAuthor which acts as a data model for one row from my table. Now let's add code to all these files.
 
Figure 12. Creating a PHP class.
Figure 12. Creating a PHP class.
The new files are created and opened for editing in Eclipse. Here is the code for MyService class (you need to update the connection information for your specific database setup; to do this, look for the four constants at the top of the class):
 
<?php require_once 'VOAuthor.php'; class MyService { /** * Retrieve all the records from the table * @return an array of VOAuthor */ public function getData() { //connect to the database. //we could have used an abstracting layer for connecting to the database. //for the sake of simplicity, I choose not to. $mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD); mysql_select_db(DATABASE_NAME); //retrieve all rows $query = "SELECT id_aut, fname_aut, lname_aut FROM authors_aut ORDER BY fname_aut":; $result = mysql_query($query); $ret = array(); while ($row = mysql_fetch_object($result, "VOAuthor":)) { $ret[] = $row; } mysql_free_result($result); return $ret; } /** * Update one item in the table * @param VOAuthor to be updated * @return NULL */ public function saveData($author) { if ($author == NULL) return NULL; //logMe($author); //connect to the database. $mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD); mysql_select_db(DATABASE_NAME); if ($author->id_aut > 0) { //save changes $query = "UPDATE authors_aut SET fname_aut='":.$author->fname_aut.":', lname_aut='":.$author->lname_aut.":' WHERE id_aut=":. $author->id_aut; } else { //add new record $query = "INSERT INTO authors_aut (fname_aut, lname_aut) VALUES ('":.$author->fname_aut.":', '":.$author->lname_aut.":')":; } $result = mysql_query($query); return NULL; } } ?>
Let's create the code for the Value Object, the data model. Select the file VOAuthor.php and paste this code:
 
<?php class VOAuthor { public $id_aut; public $fname_aut; public $lname_aut; } ?>
As you can see, this class is very simple; it just provides the same members as the fields from the table. When you use remoting, you get for free the casting of the data to the right type. For example: MyService.getData() method returns an array of VOAuthor PHP objects. However, as you will see later, in Flex the result is an array of VOAuthor ActionScript objects.
 
 
Creating the Flex application
Now that you have the PHP code in place, you are ready to create the Flex code that will call the PHP class. What I want to have is a Flex application that uses a data grid to display the data and a form to edit one row.
 
First, be sure to select the Flex perspective from the top right icons of Eclipse. Fortunately, in Flash Builder 4 there are some new wizards that assist you when you want to consume PHP services. This wizards are accesible via the new Data/Services view (see Figure 13). If you don’t see this view, go to Window > Other views… and select Data/Services entry from the Flash Builder node.
 
Figure 13. Data/Services view.
Figure 13. Data/Services view.
Then, open the flex_php.mxml file and select Design view. Next, add a DataGrid component from the Components view by draging the DataGrid onto the scene (see Figure 14).
 
Figure 14. Adding a DataGrid component.
Figure 14. Adding a DataGrid component.
Now you are ready to use the first wizard in order to create a client-side service that consumes the MyService.php class. Click on Connect to Data/Service link from Data/Services view. A wizard opens and there you have to select PHP (see Figure 15) and click Next.
 
Figure 15. Connect to Data/Service&hellip; wizard first page.
Figure 15. Connect to Data/Service&hellip; wizard first page.
In the second page of the wizard use the Browse… button to select the php service, MyService.php (see Figure 16). When you click on Next a warning window pop up (see Figure 17). The Data/Service wizard uses ZendAMF part of the Zend Framework in order to enable remoting for PHP. If you click OK the wizard will install the framework for you. After the Zend Framework is installed, the wizard introspects the php service (MyService.php) and you should see the public methods from the PHP class (see Figure 18). Click Finish.
 
Figure 16. Selecting the php service class.
Figure 16. Selecting the php service class.
Figure 17. Installing Zend Framework.
Figure 17. Installing Zend Framework.
Figure 18. Instrospecting the PHP service.
Figure 18. Instrospecting the PHP service.
Now you should see the client service (called MyService) in the Data/Services view (see Figure 19). The wizard generated two classes in the services.myservice package. MyService is the class you’ll use in your application to connect to the PHP service. It extends the _Super_MyService class that does the heavy lifting. If you ever find yourself in the position to customize the class you should always change the child class and not the parent.
 
Figure 19.Client side data service.
Figure 19.Client side data service.
As you remember, on the PHP side you use a PHP data object (VOAuthor) to store one record from the database. You will use another wizard to create the equivalent ActionScript data object. To do this, right-click on the getData() node from the Data/Services view and select Configure Return Type… (see Figure 20).
 
Figure 20. Configure the return type for the getData() operation.
Figure 20. Configure the return type for the getData() operation.
On the first wizard page leave the defaults and click Next. Flash Builder 4 makes a request to the MyService php class calling the getData() method. If you don’t have any errors in your PHP script and the database credentials are correct, you should see the second page of the wizard (see Figure 21) and here you click Finish.
 
Figure 21.Creating the ActionScript data model.
Figure 21.Creating the ActionScript data model.
If you open the valueObjects package you should find two new classes VOAuthor and its super class _Super_VOAuthor. Again, if you need to customize the data object, you should add your custom code to the child class and not to the parent.
 
It is time to use these classes. Let’s bind the result of the getData() operation to the DataGrid. To do this, drag and drop the getData() node from Data/Services view onto the DataGrid (make sure you are in Design view). A confirmation window pops up (see Figure 22). Click OK and you should see the name of the properties from the ActionScript data object in the DataGrid header (see Figure 23).
 
Figure 22.Binding the getData() operation to the DataGrid.
Figure 22.Binding the getData() operation to the DataGrid.
Figure 23. getData() operation binded to the DataGrid.
Figure 23. getData() operation binded to the DataGrid.
Save the file and switch to Source view. You should see a block of ActionScript code that was generated by the binding operation. The dataGrid_creationCompleteHandler() function gets called once the Creation Complete event is triggered by the DataGrid.
 
protected function dataGrid_creationCompleteHandler(event:FlexEvent):void { getDataResult.token = myService.getData(); }
When myService.getData() is called a token is returned. The token is saved into the token property of a CallResponder instance. And the DataGrid gets the data from the lastResult property of this CallResponder instance.
 
It is time to run the application and see the data. Make sure you saved all the changes and while you are still in the Flash Perspective click on Run icon or right-click on the flex_project.mxml file and choose Run As > Web Application. You should see the DataGrid and the data in your default web browser.
 
Figure 24. Testing the application.
Figure 24. Testing the application.
So right now you have a Flex application that connects to a PHP class and displays the data stored in a MySQL table. And you done all the client code without coding a single line so far. How about adding editing capabilities to this application?
 
Let’s do this now. This time you will use the other method of the PHP class (saveData()). But before calling this method, let’s add a form next to the DataGrid. Make sure you go again in Design view and then select the VOAuthor entry from the Data/Services view > Data Types. Right-click on it and choose Generate Form… option (see Figure 25).
 
Figure 25. Start the Generate Form wizard for VOAuthor data object
Figure 25. Start the Generate Form wizard for VOAuthor data object
In the first page of the wizard leave the default options (see Figure 26) and click Next. In the second page unselect the id_aut property (see Figure 27). You don’t want to change the primary key of a record, you want only first and last name to be editable. Click Finish and you should see a form placed on top of the DataGrid. You can select the form and move it to the right of the DataGrid (see Figure 28).
 
Figure 26. Generate Form first page wizard for VOAuthor data object.
Figure 26. Generate Form first page wizard for VOAuthor data object.
Figure 27. Generate Form wizard second page for VOAuthor data object.
Figure 27. Generate Form wizard second page for VOAuthor data object.
Figure 28. Generated Form
Figure 28. Generated Form
You can change the labels and colors as you like. Once you’ve done with this, switch to Source view because you have to bind the current selected row from the DataGrind to the VOAuthor instance used as a data source by the form fields. If you take a look at the source you should find in the fx:Declarations sections a tag VOAuthor with vOAuthor as id. This is the object used by the form.
 
Add a binding tag after the Declarations tag. For the source property set the current selected item from the DataGrid cast as VOAuthor. The destination will be the vOAuthor object used by the form:
 
<fx:Binding source="dataGrid.selectedItem as VOAuthor" destination="vOAuthor"/>
Before you run the application, you have to create a listener for the click event of Submit button from the form. If you take a look at the form code, you’ll notice that the button has a listner registered called button_clickHandler but the listner is not defined. When the button is clicked you want to copy the values from the form to the vOAuthor instance and then call the saveData() operation passing along the vOAuthor as the object to be saved back to the database.
 
Switch back to Design view and right click on the Submit button and then choose Generate Service Call from the contextual menu. In the opened window make sure you select the saveData() operation and click OK (see Figure 29).
 
Figure 29. Generate Service Call for the Submit button.
Figure 29. Generate Service Call for the Submit button.
Switch back to Source view, and first make sure the Submit button has only one listner registered for the click event and then go to where the button_clickHandler function is defined (in the ActionScript code block). Add as argument the vOAuthor variable and before the service call make sure you set the text values from the form back to vOAuthor instance. The function should look like this:
 
protected function button_clickHandler(event:MouseEvent):void { vOAuthor.fname_aut = fname_autTextInput.text; vOAuthor.lname_aut = lname_autTextInput.text; saveDataResult.token = myService.saveData(vOAuthor); }
Now you are ready to test the final application. Run the application, make a selection, change the names using the form and then click on Submit button. The data should be persisted back to the MySQL database.
 
Figure 30.Editing the records.
Figure 30.Editing the records.
It will be pretty easy to add a delete() method on the PHP MyService class and use this method from the client. I leave this as the homework for you. I’ll give you some hints how to do it. Once you have the delete() method created on the PHP code (it should receive a VOAuthor object as argument) you can create a new button in Flex application. Then you can right-click on that button in design view and choose from the contextual menu Generate Service Call. A window opens and you can select the operation you want to call when the buttos is pressed. Choose delete() method and click OK. This will generate a new CallResponder instance and an event listener. Inside the event listener you need to pass the right argument, which is for this project the current selected row from the data grid. And you already have this stored by the vOAuthor object.
 
Another useful tip is this: you can use the result event listener of a CallResponder object in order to trigger other actions. For example, suppose you delete a record and once the record was deleted you want to call getData() operation. You can easily achieve this by adding a call to the dataGrid_creationCompleteHandler() function. This is the function that makes the request to the getData() method:
 
<s:CallResponder id="deleteDataResult" result="dataGrid_creationCompleteHandler()"/>
You need to make sure that dataGrid_creationCompleteHandler() function accepts calls without arguments. For this you change the argument to have a default value equal with null:
 
protected function dataGrid_creationCompleteHandler(event:FlexEvent=null):void

 
Debugging the code

When you want to debug your code, you have at least three different methods to do it using Flash Builder 4 and Zend Studio.
 
We added two new views to Flash Builder 4 that help you to debug the code: Network Monitor and Test Operation views. If don’t see these views you can add them from Window > Other Views… and look up at the views of the Flash Builder node (Network Monitor is available only in Flash Builder Premium).
 
Using Network Monitor view you can see all the communication that goes between the Flex client and the server. You can see both the raw data and the objects. If you want to use it, the first thing you have to do is to enable this feature: click on the Enable Monitor icon (see Figure 31).
 
Figure 31. Enabling Network Monitor.
Figure 31. Enabling Network Monitor.
After this, just run the application (you don’t have to do it in debug mode). As you use the application and data are exchanged with the server, you should see the requests, how long it took and data were send/received (see Figure 32).
 
Figure 32. Network Monitor in action.
Figure 32. Network Monitor in action.
Test Operation view, as the name implies, let’s you to test the available operations. Select Test Operation view and choose getData() operation and click Test. You should see the four VOAuthor objects (see Figure 33). If the operation expects arguments, then this view lets you define the arguments values.
 
Figure 33. Using Test Operation view.
Figure 33. Using Test Operation view.
The most powerful way to detect bugs is, of course, debugging. Flex debugger is a powerful tool that can help to quickly pin point and resolve bugs. Let’s see how you can debug the Flex and PHP code. First run the project in debug mode (make sure you are in the Flash perspective and then click on the Debug toolbar button or right-click on the flex_project.mxml and choose Debug As > Web Application). This will start the Flex debugger. If you set a breakpoint inside the dataGrid_creationcompleteHandler() function and run in debug mode you should see the Flex debugger in action (see Figure 34).
 
Figure 34. Flex debugger in action.
Figure 34. Flex debugger in action.
What about debugging the PHP code? You could use the PHP debugger from Zend Studio, unfortunately, for now there is a problem with debuggin both Flex and PHP code. It seems that the PHP debugger can’t locate properly the scripts included dynamicaly by the Zend Framework. As a result you won’t be able to reach the breakpoints you set in the MyService.php, getData() method for example. Once we solve this issue, I will update this article explainig how to use the PHP debugger.
 
The way I get arround this limitation is by using the following workflow:
 
  1. First I make sure that any PHP class I wrote doesn’t have syntax errors and the methods I want to use return the expected result. You can do this easily by loading in browser the service class you want to test. If you add an initialization code on that class and make a call to the method you want to test you can test the execution of the code as well. More specifically, with my setup I would load in browser this URL: http://localhost/zendamf_remote/MyService.php (this is the URL to the PHP service). If there are no syntax errors, then I can check that getData() returns what I expect to by adding this code (above class definition):
$service = new MyService(); print_r($service->getData());
  1. Another useful workflow is to have a function that logs into a flat file the variables you pass to that function. For example, I use this function:
function logMe($var) { $filename = dirname(__FILE__) . '/__log.txt'; if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; return; } $toSave = var_export($var, true); fwrite($handle, "[" . date("y-m-d H:i:s") . "]"); fwrite($handle, "\n"); fwrite($handle, $toSave); fwrite($handle, "\n"); fclose($handle); }
And if I want to log, for example, the argument that Flex sends when saveData() method is called, I just add this line inside of the saveData() method and then run the Flex application and edit a row:
 
logMe($author);
You should see something like this in the log file:
 
[10-02-18 14:20:01] stdClass::__set_state(array( 'lname_aut' => 'Corlan', 'fname_aut' => 'Mihai', 'id_aut' => '15', ))
That’s it folks! It wasn’t so hard, was it?
 

Where to go from here

Using Flash Builder and Zend Studio for Eclipse together you can create combined Flex and PHP projects and take advantage of editing Flex and PHP files in this kind of setup. As your projects grow in scope and complexity, you will be able to debug the Flex and PHP code easily and at the same time.
Go to Flex Developer Center – Learn Flex and PHP page for more articles on Flex, PHP, and AMF.