Monday, December 14, 2009

Data Centric Development with Flex, PHP and Flash Builder 4

Data Centric development is made simple with Flash Builder 4. If you have a PHP class, Flash Builder 4 allows you to create a Flex front end for it with just few clicks.


Create a table employee in your Mysql database as shown below


CREATE TABLE `employee` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(50) NOT NULL,
  `dept` varchar(50) NOT NULL,
  `emp_sal` int(11) NOT NULL,
  `manager` varchar(50) NOT NULL,
  PRIMARY KEY (`emp_id`)
)

The Employee Pojo  and the Employee Service is as shown below.

Employee.php

<?php

class Employee
{
    public $empId;
    public $empName;
    public $dept;
    public $empSal;
    public $manager;
}

?>

EmployeeService.php

<?php
include_once 'Employee.php';
class EmployeeService {

    private $connection;

    private function connect()
        {
             $connection = mysql_connect("localhost:3306",  "root",  "") or die(mysql_error());
             mysql_select_db("empdb", $connection) or die(mysql_error());
    }

    public function getAllEmployees()
    {       
          $response = array();
          $this->connect();
          $sql = "SELECT * FROM employee";
          $result = mysql_query($sql) or die('Query failed: ' . mysql_error());
            $counter = 0;
            $resultObj = null;
            if($result)
            {
                while(($row = mysql_fetch_assoc($result)))
                {
                    $resultObj = $this->createEmployeeObject($row);
                    if($resultObj != null)
                    {
                        $response[$counter] = $resultObj;
                        $counter++;                   
                    }
                }
            }
          return $response;
    }
    private function createEmployeeObject($row)
    {
        $empObj = null;
        if($row)
        {
            $empObj = new Customer();
            $empObj->empId = intval($row["emp_id"]);
            $empObj->empName = $row["emp_name"];
            $empObj->dept = $row["dept"];
            $empObj->empSal = $row["emp_sal"];
            $empObj->manager = $row["manager"];
        }
        return $empObj;
    }
}

?>

Follow the following Steps for creating the Flex Project with the Flash Builder 4.

In this screen:

  1. Set the project name to “DCDFlex”

  2. Set the Application type to “web (run in Adobe Flash Player)”

  3. Set the Application server type to “PHP”

  4. Click next to continue.

  5. In the Next screen, set the Web root to the root folder of your PHP server. Its c:\wamp\www in this sample

  6. Set the Root URL to the root URL of your PHP server. Its http://localhost in this sample

  7. Leave the Output folder to default value

  8. Click the “Validate Configuration” to validate the server details entered

  9. Click on finish to continue.

  10. Once the project is created, to create a service, Select the Data/Services window. If this is not visible, select it from Window -> Data/Services

  11. Click on “Connect to Data/Service” in the Data/Services window

  12. Since we want to communicate with the PHP we created, select PHP and click on next button.

  13. Browse and select the PHP file to use. Make sure the PHP file is deployed in your web application

  14. Click on next button to continue.

You will see a window displayed, saying Zend AMF library will be installed. Just click on OK and continue will the set up. Flash Builder will deploy the Zend AMF on your PHP server.Once the installation completes, Flash Builder will display a message. Clicking OK will display the functions in the PHP class. PHP class functions are referred as “operation”.Click on finish to continue. Service created above can be seen in the services explorer. 

Configuring Return Type

In this step we will test the operation and configure the return type on the client i.e. we will specify what type of object to create with the response from the server. This will make it easy for us to develop, since it is easier to deal with strong typed objects.

Right click on the “getAllEmployees” operation in the services explorer and select “Configure return type” A window will be launched with options to configure the return type. You can chose an existing data type or let the Flash Builder generate VO classes based on the response from the server. Let’s leave it to the Flash Builder to generate required VO classes based on the server response. Click next to continue. You can see the response from the server in the window. Flash Builder introspected the Employee object returned from the server. Just click on finish. You can see the return type of the operation changed. When we invoke the “getAllEmployees” operation, response will be object of the type “Customer”, in our case ArrayCollection containing Employee objects.

Displaying or binding service results in UI controls

We usually write code to display the response from the service in a DataGrid or any other control. Flash Builder 4 has an awesome option which allows you to just bind a service response to a control.

  1. Switch to design view

  2. Change the Application layout to “vertical” using the properties panel

  3. Drag and drop a “DataGrid” from the “components” panel on to the design area

  4. Set the width and height properties of the “DataGrid” to 100%

Right click on the DataGrid and select “Bind to Data …”. A window will be opened.

  1. We select a “New service call” because there are no existing services in the current application.

  2. Select the “EmployeeService”

  3. Select “getAllEmployees():Employee[]” from the operations list

  4. Click OK

You can see the DataGrid in the design updated with properties of the Employee object. That’s all about it. We are done, and a DCD Flex application is ready with PHP as the backend in just a few minutes.

The Flex code is as below for your reference

<?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/halo" minWidth="1024" minHeight="768" xmlns:employeeservice="services.employeeservice.*">
    <s:layout>
        <s:VerticalLayout/>
    </s:layout>
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.controls.Alert;

            protected function dataGrid_creationCompleteHandler(event:FlexEvent):void
            {
                getAllEmployeesResult.token = employeeService.getAllEmployees();
            }

        ]]>
    </fx:Script>
    <fx:Declarations>
        <s:CallResponder id="getAllEmployeesResult"/>
        <employeeservice:EmployeeService id="employeeService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <mx:DataGrid width="100%" height="100%" id="dataGrid" creationComplete="dataGrid_creationCompleteHandler(event)" dataProvider="{getAllEmployeesResult.lastResult}">
        <mx:columns>
            <mx:DataGridColumn headerText="empName" dataField="empName"/>
            <mx:DataGridColumn headerText="manager" dataField="manager"/>
            <mx:DataGridColumn headerText="empSal" dataField="empSal"/>
            <mx:DataGridColumn headerText="empId" dataField="empId"/>
            <mx:DataGridColumn headerText="dept" dataField="dept"/>
        </mx:columns>
    </mx:DataGrid>
</s:Application>

2 comments:

Ed Sullivan said...

Nice post. Would love to see some of your stuff in the Adobe Flex Cookbook; http://www.adobe.com/go/flex_cookbook.

Best regards,

Ed Sullivan
Adobe Systems

Ram said...

@Ed, Thanks Ed. Will surely try to update the cook book.