Requirements      
Prerequisite knowledge Required products
Sample files User level
Basic knowledge of Flex will be helpful, but it is not required for this tutorial. Some experience with MySQL administration, however, is needed.
Flash Builder (Download trial)
 
Intermediate
       

 

Note: This article was written using Flex 4 and/or Flash Builder 4, however, the information described here is still valid for Flex 4.5 SDK and/or Flash Builder 4.5 though some minor changes might be necessary.
 
The data-centric development features of Adobe Flash Builder 4 allow you to connect to your Flex applications to multiple back ends with minimal coding, but the database introspector for PHP takes it to a whole new level by generating back end sample code. After you specify the database access details and the name of the table you want to use, Flash Builder 4 will create the PHP methods for creating, reading, updating, and deleting data from your database. This code is placed onto your server where you can edit it as you require.
 
Flash Builder 4, the new version of the IDE formerly known as Flex Builder, comes with new features designed to bridge the designer developer gap. Together with the data-centric development features, which enable a more data-oriented feel to application development, these capabilities will dramatically decrease the time for building an application.
 
This article introduces the database introspector and how to use it to build a Flex application. I encourage you to try the steps as you read along.
 

 
Creating the database

Before you can use the database introspector you'll need a database. I used a database named testdb with two tables:
 
  • User
  • User_profile
You may already have a database you want to introspect, in which case you need not create a new one.
 
DROP TABLE IF EXISTS `testdb`.`user`; CREATE TABLE `testdb`.`user` ( `ID` int(10) unsigned NOT NULL auto_increment, `FIRST_NAME` varchar(100) default NULL, `LAST_NAME` varchar(100) default NULL, `DISPLAY_NAME` varchar(250) default NULL, `COMPANY_ID` varchar(100) default NULL, `LOGIN_ID` varchar(250) NOT NULL default '', `LOGIN_PASSWORD` varchar(45) NOT NULL default '', `DEPARTMENT` varchar(100) default NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; INSERT INTO `testdb`.`user` (`ID`,`FIRST_NAME`,`LAST_NAME`,`DISPLAY_NAME`,`COMPANY_ID`,`LOGIN_ID`, `LOGIN_PASSWORD`,`DEPARTMENT`) VALUES (1,'Prashant','Singh','Prashant Singh','1','prkumar','*****','Flex'), (2,'Shyam','Prasad','ShyamP','1','Shyamp','******','Flex'), (3,'Mudit','Aggrawal','Aggrawal','17','MuditK','******','Business'), (4,'Nishad','Musthafa','Nmustafa','1','Nmustaf','******','flex'), (5,'Neha','Paliwal','Npal','1','Npal','******','Finance'); DROP TABLE IF EXISTS `testdb`.`user_profile`; CREATE TABLE `testdb`.`user_profile` ( `ID` int(10) unsigned NOT NULL auto_increment, `USER_ID` int(10) unsigned NOT NULL default '0', `BLOG_URL` varchar(300) default NULL, `DESCRIPTION` varchar(300) default NULL, `TWITTER_URL` varchar(300) default NULL, PRIMARY KEY (`ID`), CONSTRAINT `FK_COURSE_USAGE_USER` FOREIGN KEY (`USER_ID`) REFERENCES `user` (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;
You can also use the create_testdb.sql file, which is included with the sample files for this article, to set up your database.
 

 
Constructing the Flex application

Now that you have a database, you can start building the front end. In this section you will learn how to create a new Flex project with a PHP back end. You would then go on to generate the PHP service using the introspector, which will give you access to the database.
 
 
Creating the Flex project
Follow these steps to create a new Flex project:
 
  1. Choose File > New > Flex Project.
  2. In the New Flex Project dialog box, type a name for your project, use the default location, select Web as the Application Type, use the default SDK, and select PHP as the Application Server Type.
  3. Click Next.
    Next you will need to configure the PHP server, by typing the Web root and the Root URL of your PHP server.
     
    For WAMP (on Windows) the default values of Web root and Root URL are as follows (see Figure 1):
     
Default server details for a WAMP back end

Figure 1. Default server details for a WAMP back end

In this case the access port for WAMP is 80, which is the default port. If you have a different port, change the Root URL accordingly.
 
  1. Type the values for your Web Root and Root URL, and then click Validate Configuration.
  2. After you have validated click Finish.
Your new project opens with some default code shown in Source view.
 
 
Generating the service
With the project created, you're ready to generate the service:
 
  1. Switch to the Data/Services view (choose Window > Data/Services if it is not open).
  2. Click Connect To Data Service (see Figure 2).
Click Connect To Data/Service

Figure 2. Click Connect To Data/Service

  1. Select PHP as the service type and click Next.
Click on the marked link to initiate DB introspector

Figure 3. Click on the marked link to initiate DB introspector

At this point if you had an existing PHP class on your local system, you could browse to it, select it, and click Finish. All methods of the service would be available to you in the Data/Services view.
 
You can, however, also generate the sample PHP code, which you'll do next.
 
  1. Click the link labeled "click here to generate a sample".
  2. In the Generate Sample PHP Service dialog box, you'll need to enter details for the database you want to introspect (see Figure 4):
    • Username: root (or any other user which has full access and all privileges to the database)
    • Password: Enter your password
    • Host Name: localhost
    • Server port: 3306 (This is the default port for MySQL, if your MySQL server is using a different port, type that port number instead)
    • Database: testdb (This is the name of the database you created earlier in this article. You can enter any valid database that is accessible by the user specified in Username)
Enter database details and click Connect To Database

Figure 4. Enter database details and click Connect To Database

  1. Click Connect To Database.
    Flash Builder 4 uses the Zend AMF Framework to access PHP classes on the server. If you don't already have Zend AMF installed, Flash Builder 4 will install it. If you are prompted, click Yes to install Zend AMF.
     
    The tables of your database will now be visible in the drop down list.
     
  2. Select the user table and click OK to introspect it.
  3. You may see a security warning that says the code is intended for prototyping applications in a trusted development environment and should not be used for production. Click OK.
  4. Click Finish to generate the service.
The service PHP code will be placed in a directory named services inside your project's output folder (on windows this would typically be c:\wamp\www\<projectName>).
 

 
Using the service

After the service is created, you can see its methods in the Data/Services view of Flash Builder 4 (see figure 5).
 
A new service with the name UserService is visible in the Data/Services view

Figure 5. A new service with the name UserService is visible in the Data/Services view

You can check the code for the PHP service and verify that all methods from the service are available here. It is easy to call these methods from Flex and use their output. Wouldn't it be even better if you could do it without having to write any code?
 
That is exactly what you can do using Flash Builder 4.
 
 
Viewing the data
You will see there is a method named getAllUser() in the UserService service. This method returns all users from the database. Follow these steps to use this method to display user data in a DataGrid control:
 
  1. Switch to Design view. You can do this by clicking the Design button above the code editor (see figure 6).
Switch to Design view

Figure 6. Switch to Design view

  1. Drag a DataGrid component from the Controls section of the Components view and drop it in the application's main design area (see Figure 7).
Drag and drop a DataGrid component onto the application

Figure 7. Drag and drop a DataGrid component onto the application

  1. To bind the data grid to the data output from the function getAllUser(), drag getAllUser() from the Data/Services view and drop it on the DataGrid control (see Figure 8).
  2. the Bind To Data dialog box, verify the name of the service and the method you want to bind to the DataGrid control. Click OK.
Drag and drop the method over the DataGrid

Figure 8. Drag and drop the method over the DataGrid

The columns of the DataGrid control will change to reflect the return type of the function. If you switch back Code view, you will see that code has now been generated for all that you have done so far. Run the application. All the data in the user table will be fetched from the database and displayed in the DataGrid control.
 
 
Fetching data on context
You might not always want to get all the data. In some cases, you may want to filter the data you retrieve based on some parameter.
 
As an example, consider a scenario in which you want to search through all data rows based on the ID. For this you would use the getUserById() method.
 
Follow these steps to see how this would work:
 
  1. Drag two other controls—one Button and one TextInput—from the Components view and drop them above the DataGrid (see Figure 9).
Place a TextInput control and a Button control above the DataGrid control

Figure 9. Place a TextInput control and a Button control above the DataGrid control

  1. Select the TextInput and for its id property, type txtInput in the Properties view on the right (see Figure 10). (This step is required because you will need to refer to this TextInput control later by its ID.)
Changing the ID property of the TextInput control

Figure 10. Changing the ID property of the TextInput control

  1. Double-click the Button and change its label text to Search.
    When this button is clicked at runtime, you want the application to call the getUserById() method with the data in the TextInput control as the argument. The DataGrid should then be repopulated with the new data returned from the method.
     
  2. With the button selected, click the lightning button next to On Click in the Properties View and select Generate Service Call (see Figure 11). (Alternatively, you can right-click the button and select Generate Service Call.)
Generating a service call for the Search button

Figure 11. Generating a service call for the Search button

  1. Select getUserById()as the operation (see Figure 12) and click OK.
Selecting the getUserByID() method

Figure 12. Selecting the getUserByID() method

Flash Builder 4 will switch to Code view, where you will need to type the value of the argument that will be sent to the server (see Figure 13).
 
Replace the parameter for getUserByID

Figure 13. Replace the parameter for getUserByID

What you want to send as the parameter is an integer version of the text inside the TextInput control. The value txtInput.text holds the data as a string, so you'll need to convert it to an integer before you send it using parseInt().
 
  1. In the editor, type parseInt(txtInput.text) as the argument to the getUserByID() call.
    All that remains is to switch the data in the data grid to this new data. This can be done by changing the dataProvider property of the DataGrid control.
     
    Look again at the code for the method call:
     
getUserByIDResult.token = userService.getUserByID(parseInt(txtInput.text));
You can see that the result of the service call gets stored in the token property of getUserByIdResult, which is a CallResponder. This component helps you manage the results for asynchronous calls. To access the result you can use the lastResult property of the CallResponder.
 
When there is a result for the getUserById() method call, you want to change the dataProvider property of the DataGrid to getUserByIdResult.lastResult.
 
  1. Locate the CallResponder for getUserByIDResult in Code view and add the following code to it (see Figure 14):
result="dataGrid.dataProvider= getUserByIDResult.lastResult"
Adding code to getUserByIDResult CallResponder

Figure 14. Adding code to getUserByIDResult CallResponder

Now, when the result event is fired (indicating that a result has been successfully returned from the service), the value of dataProvider property of the DataGrid control will be changed to the value of the lastResult property of the CallResponder for getUserByIDResult.
 
When you run this code, you will see that all the database rows are fetched initially. You can now search based on the ID by typing the ID in the TextInput control and clicking the Search button.
 

 
Where to go from here

In this article you learned how to generate a sample back end PHP service using the Flash Builder 4 database introspector. You also learned how to use operations provided by this service in your Flex application. Visit Anirudh Sasikumar's blog to learn how to do the same for a ColdFusion back end. To connect a Flex application to PHP servers on the back end, read the series Flash Builder 4 and PHP.
 
Flash Builder 4 makes the development of Web and desktop applications much easier and greatly reduces the time required to build an RIA. If you are just getting started with Flash Builder 4, you may want to check out some of the resources in Flex Developer Center. If you run into any problems, you can also request answers at Adobe Cookbooks.