# Flash Builder 4 and Flex 4 Bible- P20

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:50

0
86
lượt xem
16

## Flash Builder 4 and Flex 4 Bible- P20

Mô tả tài liệu

Flash Builder 4 and Flex 4 Bible- P20: When Macromedia first released Flash MX in 2002, the product was branded as the new way to build Rich Internet Applications (known by the acronym RIA). The term was invented at Macromedia to describe a new class of applications that would offer the benefits of being connected to the Internet, including access to various types of Web-based services, but would solve many of the nagging issues that had been inherent in browser-based applications since the mid-1990s....

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: Flash Builder 4 and Flex 4 Bible- P20

1. Chapter 29: Integrating Flex Applications with PHP FIGURE 29.11 Configuring the PHP server 5. Make sure the Web server that hosts PHP is running, and then click Validate Configuration to ensure that Flash Builder can reach the Web server. The output folder can be set to any location within the Web server’s document root. The default out- put folder name starts with the project name and ends with -debug to indicate that the output folder contains the debug version of the application. For example, the default out- put folder in the chapter29 project is placed under the PHP Web root with a name of chapter29-debug. 6. Click Next. 7. Select a Main application filename, and click Finish to create the project and main application. When you create your PHP pages, they can be placed in the project’s source root folder. During the compilation process, the PHP pages are recognized as application resources and copied to the project output folder from which they’re called at runtime. On the Web If you want to try the sample applications from this chapter, extract the files from the Web site’s chapter29. zip file into the new Flex project’s root folder. n 921
2. Part IV: Integrating Flex Applications with Application Servers Using PHP with HTTPService and XML You can integrate Flex applications with PHP using the Flex SDK’s HTTPService component and PHP pages that generate structured XML-based content on the server. To return structured data from a PHP page, you can either generate your own XML content with conventional text concatenation or you can use a more reliable approach that requires an external library to serialize XML packets. Using the PHP SimpleXML extension The PHP page in Listing 29.1 uses a PHP5 extension named SimpleXML to generate and return an XML-formatted response with literal values in each of the XML elements. The header() function is used to inform the client application that the content is being delivered with the xml/text content type. Web Resource The documentation for the PHP SimpleXML extension is available on the Web at http://us3.php.net/ simplexml. n LISTING 29.1 A PHP page that returns simple XML You Grow ‚em, We Mow ‚em Lawn Mowing How High the Shingle Roofing Ma &amp; Pa Kettle Cooking Supplies XML; header(“Content-type: text/xml“); echo $xmlstr; ?> 922 3. Chapter 29: Integrating Flex Applications with PHP On the Web The code in Listing 29.1 is available in the Web site files as ReturnSimpleXML.php in the src folder of the chapter29 project. n To request this XML-formatted content in a Flex application, use the Flex framework’s HTTPService component. Set the HTTPService object’s url property to the location of the PHP page: Retrieving XML data with HTTPService Retrieving the data from the server is a simple matter of calling the HTTPService object’s send() method and handling the returned results with a binding expression or a result event handler. The Flex application in Listing 29.2 retrieves the data in XML format from the PHP page and displays it in a DataGrid control. LISTING 29.2 Retrieving XML-formatted data from PHP continued 923 4. Part IV: Integrating Flex Applications with Application Servers LISTING 29.2 (continued) On the Web The code in Listing 29.2 is available in the Web site files as GetSimpleXML.mxml in the default package in the src folder of the chapter29 project. n Tip If you prefer to parse the returned XML with E4X syntax, set the HTTPService component’s resultFormat property to a value of e4x. n Cross-Reference See Chapter 22 for more information on working with data using the HTTPService component. n Using PHP and Remoting with Zend AMF There are a number of PHP implementations of the technology that are variously known as the Remoting Service (in BlazeDS and LiveCycle Data Services) or Flash Remoting (in ColdFusion). They include: l AMFPHP. A free, open-source project available at www.amfphp.org. l SabreAMF. A free, open-source project available at http://osflash.org/sabreamf. l WebOrb. A commercial implementation of Remoting for PHP, Java, ASP.NET, and Ruby on Rails that’s available at www.themidnightcoders.com. l Zend AMF. A part of the free, open-source Zend Framework available at http:// framework.zend.com/download/amf. Developers typically switch from using the HTTPService component and generic XML to an imple- mentation of AMF when they want better performance in applications that exchange data with a server at runtime. As with Flash Remoting in ColdFusion, described in Chapter 28, and the Java- based Remoting Service in LiveCycle Data Services and BlazeDS, described in Chapter 26, messages that use binary AMF are significantly smaller than an equivalent message formatted in SOAP or generic XML. The result is faster exchange of data and decreased use of network resources. The details of implementation on the server are different for each of these server-based software packages. In order to support PHP AMF services, Flash Builder 4 automatically installs a version 924 5. Chapter 29: Integrating Flex Applications with PHP of Zend AMF into your PHP server. From that point, it’s very easy to create server-side PHP code that exchanges data with your Flex application using the binary AMF protocol. Note The effort to provide AMF support for the Zend Framework was sponsored by Adobe starting in 2008 and was based on the existing codebase of AMFPHP. Because Zend AMF is now approved for use by Adobe Systems and support for it included in Flash Builder 4, upgrades and maintenance of other open-source implementations of AMF for PHP have either slowed down or completely ceased. WebOrb for PHP from The Midnight Coders remains a robust commercial option. n Installing Zend AMF The easiest way to install Zend AMF into your PHP server is to ask Flash Builder 4 to generate a PHP data connection. As described in Chapters 22, 26, and 28, a data connection is built as a set of ActionScript proxy and value object classes that you call from your Flex application. The result- ing ActionScript code uses the Flex SDK’s RemoteObject class to exchange messages in the binary AMF format. Follow these steps to trigger the installation of Zend AMF: 1. Make sure you have a currently active Flex project that’s integrated with PHP. 2. Choose Data ➪ Connect to PHP from the Flash Builder menu. 3. In the Configure PHP Service dialog box, shown in Figure 29.12, click the link to generate a sample service. FIGURE 29.12 The Configure PHP Service dialog box 925 6. Part IV: Integrating Flex Applications with Application Servers 4. In the Generate Sample PHP Service dialog box, shown in Figure 29.13, select Generate from template. FIGURE 29.13 The Generate Sample PHP Service dialog box 5. Click OK. As shown in Figure 29.14, a message dialog box tells you that a file named SamplePhp. php will be created in your project’s output folder under a subfolder named services. 6. Click OK. FIGURE 29.14 A message indicating the name and location of the sample PHP service file 926 7. Chapter 29: Integrating Flex Applications with PHP As shown in Figure 29.15, the next message tells you that Flash Builder will install Zend AMF as a PHP library. 7. Click OK. The installation of the Zend Framework now proceeds and takes a few minutes. 8. When you see the dialog box indicating that the installation is complete, click OK. FIGURE 29.15 A message indicating that Zend AMF will be installed into your PHP server 9. If you see a message indicating the version of the installed software, click OK again. 10. When the Configure PHP Service screen appears, click Cancel for now. Web Resource The Zend AMF library is installed in a ZendFramework subfolder under the Web server’s document root folder. For security and maintenance reasons, you might want to move the Zend Framework out of the Web server’s document root folder. The following Web page has a good discussion of various options and their pros and cons: http://devzone.zend.com/article/4683 n Creating a service class in PHP Zend AMF services are built as basic PHP classes. Functions declared as class members return val- ues that are encoded in binary AMF for exchange with a client Flex application. Just as with any PHP file, you don’t need to compile or otherwise prepare a PHP class to be called as a service. You just create the file in the correct location, and it’s immediately ready for use. The file must conform to these requirements: l The file must have an extension of .php. l It must be placed in a folder named services. The location of the services folder can be anywhere within the PHP server’s document root but typically is placed in the project’s output folder. The PHP class in Listing 29.3 implements a single sayHello() function that returns a string value to the client application. 927 8. Part IV: Integrating Flex Applications with Application Servers LISTING 29.3 A simple Hello World PHP class that’s compatible with Zend AMF On the Web The code in Listing 29.3 is available in the Web site files as HelloWorld.php in the services package of the chapter29 project. n Tip If you try to open a PHP file from Flash Builder’s Package Explorer view by double-clicking it, it will open in whatever software application the current operating system has registered for the .php file extension. If you want to open the file directly within Flash Builder, right-click the file and choose Open With ➪ Text Editor from the context menu. n Calling a PHP class with RemoteObject You call an AMF service’s methods using the RemoteObject component. The behavior and func- tionality of the RemoteObject component on the client is exactly the same as when you use it with Java or ColdFusion. Cross-Reference Because the client-side code for using the RemoteObject component is pretty much the same regardless of the language or platform on the server, many details of the client-side code aren’t covered in this chapter. See Chapters 24 and 26 for more client-side code samples. n Whether you declare your RemoteObject instance in MXML or ActionScript, you set the object’s endpoint property to a file named gateway.php. The object’s destination and source properties are then set to the name of the PHP service file, without the .php extension. For exam- ple, the file HelloWorld.php is referenced with the following RemoteObject declaration: The application in Listing 29.4 declares a RemoteObject component instance in MXML code and sets its source to the location of the HelloWorld service installed previously. When the user clicks the button labeled Say Hello, a call is made to the PHP class’s sayHello() function. The returned string is then displayed in the Label control using a binding expression. 928 9. Chapter 29: Integrating Flex Applications with PHP LISTING 29.4 A Flex application calling a Zend AMF service On the Web The code in Listing 29.4 is available in the Web site files as HelloWorld.mxml in the default package in the src folder of the chapter29 project. n Returning complex data from Zend AMF You can return complex data from PHP either by manually constructing an array to return or by generating and returning a simple data set. On the Web The PHP classes used in this section and in a later one on Flash Builder data connections depend on a database named contacts. You can import the structure and data for this database into your copy of MySQL using the contacts.sql file that’s included in the database folder included in chapter29.zip. n The PHP service class in Listing 29.5 executes a simple query and returns its data. LISTING 29.5 Returning a simple data set from a PHP class 10. Part IV: Integrating Flex Applications with Application Servers LISTING 29.5 (continued) return mysql_query(sprintf( “SELECT personid, firstname, lastname FROM person ORDER BY lastname, firstname”)); } } ?> On the Web The code in Listing 29.5 is available in the Web site files as DataManager.php in the services package in the chapter29 project. n When you call the service function, the query result is received in Flex as an ArrayCollection. The Flex application in Listing 29.6 calls the service function and uses debugging code to deter- mine how much time elapses between sending the request and receiving the result. When you run the application in debug mode and send the request, a tracing message reports the time elapsed in Flash Builder’s Console view. LISTING 29.6 A Flex application receiving complex data 11. Chapter 29: Integrating Flex Applications with PHP var endTime:Number = (new Date()).getTime(); elapsedTime = endTime - startTime; myData = event.result as ArrayCollection; } ]]> On the Web The code in Listing 29.6 is available in the Web site files as GetComplexData.php in the default package in the src file of the chapter29 project. n Figure 29.16 shows the resulting application, displaying data returned from the MySQL database. FIGURE 29.16 Data returned from PHP and MySQL 931 12. Part IV: Integrating Flex Applications with Application Servers Understanding ActionScript to PHP data serialization The PHP mysql_query() function returns a PHP resource, which is serialized to an ArrayCollection when returned to Flex. Table 29.1 describes how other PHP data types are serial- ized from ActionScript to PHP and back again. TABLE 29.1 ActionScript to PHP Data Serialization ActionScript To PHP Back to ActionScript Null Null Null Boolean Boolean Boolean String String String Date Float Number Array Array Array Object Associative array Object XML String String Web Resource The documentation for Zend AMF is available at http://framework.zend.com/manual/en/zend. amf.html. n Using PHP Data Connections in Flash Builder As described in Chapters 26 and 28, and as referred to earlier in this chapter, Flash Builder 4 includes the capability to generate client-side proxy classes that can be used to make calls to PHP service classes on the server. In this section I describe both how to build data connections for exist- ing PHP classes and how to generate new classes based on the structure of MySQL database tables. Defining data connections The steps for creating a PHP data connection in Flash Builder 4 are nearly identical to those for connecting to a ColdFusion CFC as described in Chapter 28: 1. Choose Data ➪ Connect to PHP from the Flash Builder menu. 932 13. Chapter 29: Integrating Flex Applications with PHP 2. Select the PHP class you want to call from your Flex application. As shown in Figure 29.17, also set the Service name as it will be known in Flex, and the packages in which you want to generate your proxy and value object classes. FIGURE 29.17 Configuring a data connection for an existing PHP class 3. Click Next. As shown in Figure 29.18, the Service Operations screen displays the PHP service class’s functions. 4. Click Finish to generate the proxy service. If you’re working with a PHP page that returns a simple result set, the function’s return data type is set to an array of ActionScript Object by default. Follow these steps to generate a custom value object ActionScript class and use it as the function’s return type: 1. Open the Data/Services view and locate the new class. 2. Right-click on the function and select Configure Return Type. 3. In the Configure Return Type dialog box, shown in Figure 29.19, click Next to auto- detect the return type. As shown in Figure 29.20, the Configure Return Type dialog box shows the structure of the returned data. 4. Enter the name of the ActionScript class you want to create and click Finish. The return type of the function is changed in the Data/Services view. 933 14. Part IV: Integrating Flex Applications with Application Servers FIGURE 29.18 The Service Operations screen FIGURE 29.19 The Configure Return Type screen 934 15. Chapter 29: Integrating Flex Applications with PHP FIGURE 29.20 The Service Operations screen Generating a service based on a database table structure Flash Builder 4 also can create complete service classes based on an existing database table struc- ture. The resulting PHP class implements functions that retrieve data (as either an entire table’s worth of data or as a paged data set); insert, update, and delete data; and retrieve single objects based on primary key identifiers. Follow these steps to generate a PHP class that supports a single database table: 1. Make sure you’re working in a currently active Flex project that’s integrated with PHP. 2. Choose Data ➪ Connect to PHP from the Flash Builder menu. 3. In the Connect to Data Services dialog box, click the link to generate a sample service. 4. In the Generate Sample PHP Service dialog box, select Generate from database. 5. As shown in Figure 29.21, enter the Username and Password for your MySQL data- base. If you’re using WampServer or MAMP, the default user name is root. The pass- word is a blank string for WampServer and root for MAMP. 6. Enter the DNS name or IP address of your MySQL server. If it’s installed on your local system, use localhost or 127.0.0.1. 7. Set the Server port. The default for MySQL is 3306. 8. Set the database name. 935 16. Part IV: Integrating Flex Applications with Application Servers FIGURE 29.21 Setting the database credentials to generate a PHP service class 9. Click Connect to Database. 10. Select the name of the table for which you want to generate a PHP service class. 11. Set the location and name of the PHP service class. The class must be placed within the Web server’s document root folder. 12. Click OK. As shown in Figure 29.22, you’re warned that the PHP file is intended for pro- totyping applications in a trusted development environment. 13. Click OK to continue. 14. In the Connect to Data/Service dialog box, select the name of the ActionScript class you want to create. Also select the Service name and the packages in which you want to create the proxy and value object classes, and then click Next. FIGURE 29.22 A warning that the generated PHP file is intended for application prototyping only 936 17. Chapter 29: Integrating Flex Applications with PHP As shown in Figure 29.23, the Service Operations screen displays the list of functions in the generate class. 15. Click Finish to complete the operation. FIGURE 29.23 A list of the generated data access functions The PHP class and its generated ActionScript proxy class implement the following functions that you can call from your Flex application (note that the name of the database table is incorporated into many of the function names and will depend on your database table names): l count(). Returns the number of rows in the table. l createPerson($item). Creates the item in the database and returns the value of the object’s new primary key (in the case of an auto-incrementing primary key column). l deletePerson($itemID). Deletes the item in the database based on the primary value. l getAllPerson(). Returns all the rows from the table. l getPersonByID($itemID). Returns the item corresponding to the value specified for the primary key. l getPerson_paged($startIndex,$numItems). Returns $numItems rows start- ing from the$startIndex row from the table. l updatePerson(\$item). Updates the item in the database. 937