Using AMFPHP (Open Source Flash Development) Part 1

Connecting Flash and Flex applications to PHP gives your application access to PHP’s robust open source server programming language and supporting frameworks. In this topic, you will explore AMFPHP, which is an open source gateway for easily connecting your Flash Player-based application to PHP. With the experience you gain from this topic, you will be ready to start adding server-side functionality to your projects. Get ready to leverage one of the most popular open source languages within your web experience.

Introducing AMFPHP

AMFPHP was designed to allow simple to complex data communication between the Flash Player client and PHP running on a server. AMFPHP is an open source project that implements Adobe’s Action Messaging Format (AMF), which is the binary protocol that Flash Player uses to handle objects. AMFPHP is an alternative to Adobe’s LiveCycle Data Services ES, BlazeDS, and Flash Remoting, with PHP as the endpoint rather than Java. AMFPHP allows a seamless connection between Flash Player and PHP classes. By leveraging the AMF protocol, AMFPHP doesn’t require any additional client-side work in order to encode and decode data objects that are sent to and from the server. AMFPHP acts as a gateway to PHP and, through a process known as serialization, transforms the data types between ActionScript into PHP data types on incoming messages and then transforms the data back for returning data. In addition to writing your own PHP classes with AMFPHP, you can leverage the extensive resources found in open source PHP classes, applications, and frameworks.


Generally, AMFPHP applications implement an n-tiered architecture. The following illustration depicts such an architecture, separated into a thin client/presentation tier (in Flash Player), a middle tier composed of AMFPHP and the business logic located in your PHP services, and a data tier that could be a combination of databases, SOAP services, and other data services that PHP can consume.

tmpeeee-264

What are the benefits of AMF?

AMF is a binary file format representing a serialized ActionScript object. The AMF file type is used throughout Flash Player for data storage and data exchange. For example, in Flash Player, AMF is used in SharedObject, RemoteObject, LocalConnection, ByteArray, RTMP, and all RPC operations. Some of the benefits of AMF include the following:

■    File size: AMF objects are very small and are compressed using zlib.

■    Fast serialization/deserialization: AMF is transformed using native C code in Flash Player, making it very fast. AMF was designed to serialize and deserialize quickly under low memory and slower CPU conditions, making it perfect for the Web. AMF data is parsed directly into objects, meaning there is no lag for interpreting or parsing AMF, making the creation of objects complete in a single pass.

■    Native types and custom classes supported: You can serialize any object in Flash Player with the only exception being DisplayObject. You can also map serialized objects back to custom class instances provided the custom class is in Flash Player when the AMF object is deserialized.

AMF 3, the default serialization for ActionScript 3, provides various advantages over AMF 0, which is used for ActionScript 1.0 and 2.0. AMF 3 sends data over the network more efficiently than AMF 0. AMF 3 supports sending int and uint objects as integers and supports data types that are available only in ActionScript 3, such as ByteArray, ArrayCollection, and IExternalizable. AMF 3 now utilizes zlib compression for faster transfer to the server. AMF is a generic term because it is accurate for both versions; however, the context of the application such as Flex or Flash CS3 implies AMF 3, whereas Flash 8 or Flash MX implies AMF 2 because AMF 3 did not exist then.

What are the benefits of using AMFPHP?

You will gain several benefits if you choose to use AMFPHP as your method of bringing server data into your Flash application. Some of these reasons could be more significant to your development team than other teams.

■    It handles the conversion of data types between ActionScript and PHP.

■    It can convert complex objects, and it supports class mapping.

■    It allows you to make direct calls to server-side methods, which eliminates time spent developing parsers in Flash and PHP.

■    AMF serialization is part of Flash Player, which decreases the code footprint and optimizes server communication.

■    It is simple to start using on any web server that runs PHP 5.2.3 or newer.

■    Services are “nonspecific” PHP classes that are portable without any code change.

■    It easily separates the workload of ActionScript programmers from PHP programmers and lets each use best-of-breed tools for development.

The requirements for using AMFPHP in the examples

The following sections use ActionScript 3 and AMF 3 for the examples. I will be using Flash CS3 as the example IDE because it is the most common development environment for Flash applications. One of the joys of AMFPHP is that the services can be consumed by either Flash or Flex. The examples provided here are tailored toward showing how AMFPHP works, not at specific ways of using the Flash or Flex framework to consume services. Each of these examples is similar to how you would build them in Flex, and they use the same AMFPHP information. Later in the topic, I will review how to connect to these same services in Flex but will focus on Flex and not the PHP service created in the Flash examples. Included in the topic download file (at http://www.friendsofed.com) is the Flex version of the example, and you’ll find plenty of comments throughout the code that will allow you to understand what each section does. For complex projects, I recommend you use a framework that implements the Service Locator design pattern. In Flash, you should use the ActionScript 3 Lightweight Remoting Framework (http://osflash.org/as3lrf) from Danny Patterson or SSR (http://osflash. org/projects/ssr). In Flex it is worth taking your time to understand Adobe’s Cairngorm framework (http://labs.adobe.com/wiki/index.php/Cairngorm), because it is a great aid in developing scalable and maintainable applications.

Getting started

In the following sections, I’ll show you how to install and configure AMFPHP. Then, since the best way to start learning a new technology is to start with the fundamentals, I’ll show a working “Hello, World”-style example so you can make sure your installation is configured properly

Installation requirements

AMFPHP runs on a web server with a PHP release newer than 5.2.3. AMFPHP does not require any special configuration to the PHP environment for it to perform. A PHP module called AMFEXT speeds up data communication, but this is an optional performance module.

AMFPHP does not require any special components or libraries in ActionScript 3. Everything that is necessary for AMF data communication is now part of the language, as opposed to ActionScript 2, which required the installation of the Flash remoting components. Ifyou have a copy of Flash CS3 or Adobe Flex 2 or 3, you are ready to follow these examples.

Server configuration

With access to a PHP 5.2.3 (or newer) web server, installing AMFPHP is as fast as you can place the files on the server. Throughout the following examples, I will use http://localhost/ as the domain of your web server. For speed of development, I recommend that you configure your computer with a web server and PHP. If you have never configured a web server, I suggest you try Apache2TRIAD (http://www.apache2triad.net) or XAMPP (http://www.apachefirends.org), which is a packaged installation to get your own development environment running quickly. Ifyou choose to use a remote server or use virtualization of another operating system, replace http://localhost/ with the URL to your own web server in each example.

The first thing to do is download AMFPHP 2.0 (or newer) from SourceForge (http://sourceforge. net/project/showfiles.php?group id=72483).

Then create a project folder for the examples on your desktop or your preferred location, and unzip the download to reveal a folder called amfphp. This folder holds everything necessary to install the application, as shown in the following screenshot.

Transfer the amfphp folder into the document root of your web server. Many examples on the Web rename the amfphp folder to flashservices when they place the contents on the server. For simplicity’s sake, I will keep it as amfphp in this example.

Now you need to create a cross-domain policy file so that Flash Player can alter the HTTP header when it connects to the AMFPHP service. Adding the following crossdomain.xml file to your website allows the sending and receiving of custom headers from Flash to your server.

tmpeeee-265[3]

Please make sure you have a policy file in the document root of the web server on which to host your amfphp services. Add the following XML to a file called crossdomain.xml. Update the domain name to the name of the web server that hosts your SWF file.

tmpeeee-266

Testing the server installation

Using a web browser, load the gateway.php file in the folder you just uploaded. Ifyou are developing locally, you can load http://localhost/amfphp/gateway.php. If the installation is working properly, you will see the following content in your web browser. Otherwise, you have a PHP configuration error on your server. Review the “Debugging” section later in this topic if you do not see the following page.

tmpeeee-267

It’s installed!

That’s all there is to getting AMFPHP installed on your server. Next, I will show how to write your first remote service for ActionScript to consume.

Creating your first service

AMFPHP allows ActionScript to instantiate remote PHP classes. There is nothing unique about the class files that AMFPHP consumes, which makes them highly portable to other projects. As long as there are public methods in the class file, ActionScript will be able to use those methods.

The following example is a PHP class file called HelloWorld with a single public function called say. The method say takes a string as a parameter and then returns what was said with the day of the week.

tmpeeee-268

Open your favorite PHP text editor, and create the contents of the HelloWorld class. The file is also included in the topic download file (http://www.friendsofed.com). Save the file as HelloWorld. php, and upload it to your web server into the amfphp/services/ folder to add the class to your AMFPHP installation. I always like to test new classes to make sure nothing is wrong with what was uploaded. Use a web browser, and go to http://localhost/amfphp/services/HelloWorld.php, where you should see a blank web page because the class ran properly and does not have any output. If you see errors, you will need to investigate what went wrong. Review the “Debugging” section later in this topic if the server throws any errors.

Using the Service Browser tool

AMFPHP comes with a Flex-based Service Browser for testing services. This is a great tool to speed your PHP development and also ensure that everything on the server is working properly.

To access the Service Browser, go to http://localhost/amfphp/browser/index.php with a web browser that has Flash Player 9 or newer enabled. Before the Service Browser opens, you will be prompted to make some configuration choices, as shown in the following screenshot.

tmpeeee-269

You do not need to change any of these selections. Click Save to access the Service Browser. On the left side, select HelloWorld. This is the file that you just created. Notice on the left that it has a list of methods and the inputs necessary to test the methods. You can test the service by typing anything into the sMessage input field and clicking Call.

tmpeeee-270

The results from the service appear in the text area on the Results tab, as shown in the following screenshot. The Info tab shows how long it took to execute the command on the server.

tmpeeee-271

At this point, you have a properly installed installation of AMFPHP and a working remoting service. The next step is to set up a simple connection from Flash.

Consuming HelloWorld

It’s time to put the entire process together! I’ll show how to create the UI elements in Flash first and then create a Main.as class file that will make the connection to AMFPHP and populate the UI components. Follow these steps:

1.    Open Flash CS3, and create a new Flash file (ActionScript 3).

2.    Save the document as HelloWorld.fla in a new folder.

3.    Create a new ActionScript file by selecting File > New > ActionScript File.

4.    Save the file, and name it Main.as.

5.    Select the HelloWorld.fla tab to continue working on the interface.

6.    In the Components window, drag a user interface TextInput component to the stage. This will be the input field for the text to be sent to the server.

7.    Place the TextInput component in the top-left corner. In the Properties Inspector, give the component the instance name of server_txt, and change the Text property to AMFPHP is Easy.

8.    Drag a Button component to the right of the server_txt component. Change the Button component’s instance name to send_btn. Change the label of the Button component to send to server.

tmpeeee-272

9. Drag a TextArea component to the stage below the server_txt component. Change the instance name to response_txt, and change the width of the TextArea to 200.

10. Select the stage by clicking it. This opens the stage Properties Inspector at the bottom of the Flash CS3 IDE.

tmpeeee-273

11.    Change the stage width to 300 and height to 200.

12.    From the stage Properties Inspector, also change the Document class to Main. This links the

Main.as ActionScript file with the user interface HelloWorld.fla.

13.    When you are done, you should have a HelloWorld.fla file and a Main.as file located in a single folder. Your HelloWorld.fla file should look similar to the    following screenshot.

tmpeeee-274

Next post:

Previous post: