Creating PHP services for client applications



You can create applications with Flex that access services from a wide variety of technologies. These technologies include:

  • ColdFusion

  • PHP

  • HTML (REST-style) services

  • Web services (SOAP)

After creating a service, it is a good idea to test the service before accessing it from a client application.

The principles of creating and testing PHP services can be applied to other service technologies.

Create a PHP class that implements a service

The service you create in this tutorial accesses the fb_tutorial_db database. For information on installing this database, see Installing the tutorial database.

  1. In your web root, create a folder named PHP_Service. Within that folder, create another folder named services.

  2. In your favorite PHP editor, create the following PHP class:

    <?php 
    class EmployeeService { 
        public function getEmployees() { 
            $connection = mysqli_connect("localhost", "USER", "PASSWORD", 
                        "fb_tutorial_db") or die(mysqli_connect_error()); 
     
            $sql = "SELECT * FROM employees"; 
            $result = mysqli_query($connection, $sql) 
                or die('Query failed: ' . mysql_error($connection)); 
     
            $rows = array(); 
            while ($row = mysqli_fetch_object($result)) { 
                $rows[] = $row; 
            } 
            return $rows; 
     
        } 
    } 
    ?>

    This is not an exercise in object-oriented programming with PHP. The PHP class contains functions that implement data service operations. Flex introspects the service operations in the PHP class to create ActionScript classes in the client application. The client application access the data service using these ActionScript classes.

  3. Save the PHP file as EmployeeService.php and place it in the following location:
    <Web Root>/PHP_Service/services/EmployeeService.php
    Note: Make sure the filename corresponds to the name of the class implementing the PHP service.
  4. In EmployeeService.php, examine the code that makes a call to the database and that handles the data returned by the operation.

    • Call the database:

          $sql = "SELECT * FROM employees"; 
          $result = mysqli_query($connection, $sql) 
              or die('Query failed: ' . mysql_error($connection)); 

      This is a basic PHP call to a database, returning a result set.

    • Handle the data returned by the operation:

          $rows = array(); 
          while ($row = mysqli_fetch_object($result)) { 
              $rows[] = $row; 
          } 
          return $rows; 

      Flex expects data returned by the operation to be an object or an array of objects. The PHP code that handles the returned result set iterates through the result, returning an array of objects. Each object in the array corresponds to a retrieved record from the database, containing values for each column in the record.

Test the PHP service

It is always a good idea to test a service before you access it from an application.

  1. Create a PHP script file, tester.php, that calls the service and displays the returned data.

    <pre> 
    <?php 
        include('PHP_Service.php'); 
        $o = new PHP_Service(); 
        var_dump($o->getemployees()); 
    ?> 
    </pre>
  2. Save tester.php in the same folder as EmployeeService.php, and call the service from a web browser.

    If the call is successful, tester dumps records from the database:

    array(999) { 
    [0]=> 
        object(stdClass)#4 (6) { 
            ["emp_no"]=> 
            string(5) "10002" 
            ["birth_date"]=> 
            string(10) "1964-06-02" 
            ["first_name"]=> 
            string(7) "Bezalel" 
            ["last_name"]=> 
            string(6) "Simmel" 
            ["gender"]=> 
            string(1) "F" 
            ["hire_date"]=> 
            string(10) "1985-11-21" 
        } 
    [1]=> 
        object(stdClass)#5 (6) { 
            ["emp_no"]=> 
            string(5) "10003" 
            ["birth_date"]=> 
            string(10) "1959-12-03" 
            ["first_name"]=> 
            string(5) "Parto" 
            ["last_name"]=> 
            string(7) "Bamford" 
            ["gender"]=> 
            string(1) "M" 
            ["hire_date"]=> 
            string(10) "1986-08-28" 
        } 
    [2]=> 
        object(stdClass)#6 (6) { 
            ["emp_no"]=> 
    . . .

    If there is an error in the service, PHP displays information to help locate the error.

    Warning:  mysqli_connect() [function.mysqli-connect]: (28000/1045): 
        Access denied for user 'admin'@'localhost' (using password: YES) in 
        C:\wamp2\www\PHP_Service\services\PHPservice.php on line 6 
     
    Access denied for user 'admin'@'localhost' (using password: YES)

Import the service into Flex and bind returned data to application components

The relationship between client code and server code in Flex differs from the traditional relationship in a server template.

In a traditional relationship, a server template mixes server code with client code. When the client queries a database, it dynamically embeds HTML code with returned data.

Flex, however, separates client code from server code. The remote service returns only data. Flex binds the returned data to user interface components in the client application.

  1. In Flash Builder, select File > New > Flex Project.

  2. Specify PHP_Service for the project name and set the Application Server Type to PHP.

    View full size graphic
    Specify project name and server type

    Note: If you forget to set the application server type when you create the project, you can later specify the server type from the Project Properties page.
  3. Click Next. Verify your PHP configuration and click Validate Configuration.

  4. For Output Folder, specify the PHP_Service folder you created previously.

    Flash Builder suggests a default location for the output folder. Use the location that already contains EmployeeService.php. Here is the location previously specified:

    <Web Root>/PHP_Service/
  5. Click Finish.

    The Flash builder source editor opens to PHP_Service.mxml.

  6. Select Design to open the editor in Design mode. Add a DataGrid control to the application:

    The DataGrid component is available under Data Controls in the Components view. Drag the DataGrid control to the design area.

  7. With the DataGrid selected, in the Properties view, click the Bind to Data button.

    The Bind to Data button is next to the Data Provider field in the Properties view.

  8. In the No Services Defined dialog, click Yes to connect to a service.

  9. In the New Flex Service wizard, select PHP. Click Next.

    Flash Builder provides multiple ways to connect to a data service. In this scenario, you first create the user interface. then from a user interface component, you can connect to a service and specify the remote operation.
  10. Click Browse and navigate to the PHPservice.php file you created previously. Click Finish.

    The path to the file is:

    <Web Root>/PHP_Service/services/EmployeeService.php

    The Data Services View now displays the EmployeeService.

  11. With the DataGrid selected, again click the Data Provider button in the Properties view.

    The Bind to Data dialog opens with New Service Call selected.

    EmployeeService is the only service available in the Flex project.

    getBooks() is the only operation available in the service.

  12. In the Bind to Data dialog, select Configure Return Type to define the data type for returned data.

    Flex needs to know the return data type to access service operations. The EmployeeService service does not define the data type for returned data. Flash Builder uses client-side typing to define a custom data type for the returned data.

  13. In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.

  14. Specify Employee for the name of the type. Click Finish.

    The EmployeeService returns a complex data type representing a database record for an employee. The custom type Employee provides access to each field of the record.

    View the properties of the Employee data type returned by the service. Click Finish.

    When Flash Builder configures a return type it accesses the database to create a value object. The properties of the custom data type are derived from the value object. You can view and modify the properties of the data type before proceeding.
  15. In the Bind to Data dialog, click OK.

    Flash Builder binds the data returned from the service call to the DataGrid component. It modifies the columns of the DataGrid, binding the value returned for each Employee property to a column in the DataGrid.

  16. Make sure the DataGrid is still selected. In the Properties view, click Configure Columns and then do the following steps:

    1. Select the hire_date column. Click Delete to delete the column.

    2. Similarly, delete all columns except emp_no, first_name, and last_name.

    3. Select the emp_no column. Click Up to move it to the first position.

    4. In the Header Text field, rename the column to ID.

    5. Similarly, rename the first_name and last_name columns.

    6. Click OK.

  17. With the DataGrid still selected, in the Properties view, specify False for the editable property.

  18. Select File > Save to save the application file. Then select Run > Run PHP_Service to run the application.

    The application runs in a web browser.