ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Flash MX (PHP) Remoting
http://www.actionscript.org/resources/articles/11/1/Flash-MX-PHP-Remoting/Page1.html
Jesse Stratford
Jesse was born and raised in Australia, and now lives in London. He is one of the original founders of http://ActionScript.org, and was formerly a Flash developer, teacher, author and speaker. While Jesse no longer works as a full-time Flash professional, he still enjoys actively participating in the http://ActionScript.org community as time permits.
 
By Jesse Stratford
Published on September 9, 2005
 
Tutorial details:
Written by: Jesse Stratford [email:[email protected]]
Difficulty Level: Intermediate
Requirements: Flash MX, Remoting Components (Free), AMFPHP Gateway (Free), Compatible Webhost

Page 1 of 3

Before we begin, the author would like to gratefully acknowledge the hard work of the AMFPHP team. I'd like to especially thank Patrick Mineault who proactively updated this tutorial following the release of AMFPHP 1.0, as I would not have had time to do so. If you find yourself using AMFPHP, please drop the team a quick email to say thanks!

In this tutorial, we'll examine how to integrate Flash and PHP using Flash Remoting and amfphp. amfphp and Remoting make Flash data exchange simple and efficient. Here's what we're shooting for:

Pretty cool huh? The messages are stored in a database on the amfphp website. You can post your own message (watch your language!)

Can I Complete this Tutorial?
I always do my best to make my tutorials as easy to understand as possible. In cases where not only Flash is involved this becomes more difficult because I'm not a PHP guru and I can't teach you PHP before we begin (or even as we go). Having said that, if you're an intermediate ActionScript user, the PHP code used herein shouldn't daunt you very much; while different from ActionScript, it's decipherable.
If you have some PHP experience, that's great, as it will make understanding this tutorial easier still.
If you have absolutely no idea about PHP, I'd suggest you read this tutorial anyway; what I'm trying to do is teach you the basics and the benefits of this methodology, then, if you think it's going to be useful for you, you can go off and learn PHP (which is dead easy).

So now I can cover my back and say this: I'm not going to explain every line of code in this tutorial. The code is well commented and both PHP and ActionScript are very well documented. Fool around, have a go and if you hit a wall, post questions on the Forums, that's what they are there for.

What is Flash Remoting?
Flash Remoting allows you to execute Remote Procedural Calls (RPCs) via the Flash player. It allows you to transfer serialized, type-persistent objects directly between the server and a Flash MX client. The major use for Flash Remoting is in creating Rich Internet Applications (RIAs). In other words, using Flash not just as an animation tool, or even a jazzy HTML interface, but as the GUI and client for a full-scale, service providing, Internet application.
If you've built XML-based RIAs you know how much of a pain it can be to serialize the data, debug, and integrate into your application. With Flash Remoting, you can call remote methods from the Flash client and the arguments will end up in the native remote language, and will come back to Flash correctly typed, so there's no messing with serialization at all.

What Flash MX Remoting isn't.
Flash Remoting is not the same as Flash Media Server (FMS, previously FlashCom). FMS allows for video and audio streaming and recording, Server Side ActionScript, Remote Shared Objects among other things. In a way, Flash Remoting provides data-centric exchange while FMS2 is focused on multimedia. While FMS2 can be prohibitively expensive, Flash Remoting server components are available in many languages, like PHP, Java and Python, for free.

What is PHP Remoting?
Macromedia designed Flash Remoting mainly as a direct link between the Flash player and ColdFusion MX. The message format used in Flash Remoting is called ActionScript Message Format (AMF). After the release of Flash Remoting for Java, .Net and Cold Fusion, open-source developers who favored PHP as their server-side language of choice decided to create their own gateway so that Flash MX Remoting could be integrated with PHP.
The result is the amfphp project. Since then there have been many spin-offs of amfphp, like OpenAMF, FLAP (Perl), amf4r (Ruby) and more. amfphp is now more a mature project, with a stable 1.0 release three years after its creation.

Why use Remoting?
Remoting will drastically reduce the amount of work you have to do when exchanging data between Flash and a server because it allows for direct exchange of Objects; meaning you don't have to break down delimited strings or pass lengthy XML.
Further, the AMF format used in Remoting is binary, so it is considerably less verbose than XML and XML-based methods such as WDDX serialization, so it will download faster. That's not to say XML isn't great, XML has lots of uses. However, Remoting does one thing, and one thing only, data exchange between Flash and the server, and it does it very well.
Because of its object oriented nature, Flash Remoting allows you to develop a single set of server side scripts which can serve both a Flash and a non-Flash front end for your site. You can separate the presentation and formatting of data from the application layer, creating application layer scripts which just output objects and don't care what is done with them, whether they are used by Flash or read in by another server side script and formatted for an HTML or AJAX page. If your customers want both a Flash and a non-Flash front-end for their site, look no further than Remoting.
Finally, Remoting is just easier than doing it in any other way. Less coding is involved, bug testing is made simpler and coupling is tight.

Why PHP Remoting specifically?
I spent three hours the other day learning Cold Fusion (using Macromedia's trial). I'd never touched it before. In three hours, with a good book I was able to learn basically everything I needed to make a database driven website. Cold Fusion is a great server side language but, being a proprietary product, it's not within everyone's price range (myself included at the moment).

This tutorial is really just a tutorial on Flash Remoting (whether you use PHP, Cold Fusion, .Net or J2EE is irrelevant). As far as I know, the ActionScript herein will work just fine with other server-side modules (compatible with Flash Remoting) which output objects of the same format as the PHP files used herein. I decided to go the PHP route to enforce the "assume nothing" line I use in my tutorials; specifically, "don't assume people can afford or want to buy proprietary products when they can do most of the same stuff with PHP for free". The great thing about PHP is that it's already installed on most web servers, it comes with a bunch of useful libraries, and has a very active open-source community behind it. PHP is also syntactically very close to ActionScript so it is pretty easy to learn for Flashers.

Preparing Your System
With the general introductions out of the way, let's get into it. Since this involves PHP, a server side scripting language, you are going to require an account with a web-hosting company that supports PHP (and mySQL for this tutorial), or a local web server such as Apache or IIS, with PHP and mySQL setup and running. The machine I'm on at the moment has IIS 5.0 and PHP 4.2.2 and everything works just fine.

Running a local web server is highly recommended over using an online account, because it makes testing and debugging that much easier and faster. If you've never setup a local web server before, I suggest you try a package like XAMPP which provides a free, all in one Apache, PHP and mySQL pack, preconfigured and ready to go. All you need to do is unzip the package basically. Before proceeding with this tutorial you need to make sure your server is running and working so create a new file called 'phpinfo.php' in a text editor and add the following code:

[php]<?php
phpinfo();
?>[/php]

then drop it in your local web server directory and access it via your browser (http://localhost/phpinfo.php or similar will be the URL). If it brings up a big diagnostics screen, you're in business. If not, debug. If anyone has a link to a great tutorial on setting up a local web server, please send it to me and I'll add it here. (So far users have suggested these articles: 1.)

Also, to do any sort of Flash Remoting you need the Flash Remoting Components for ActionScript 2 for Flash 8 or Flash MX 2004 which come free from Macromedia. Note that these aren't 'Components' in the standard sense of the word; they're more like an extension to the Flash Authoring environment. Resist the temptation to download the AS1 components; they are not available for Flash 8 and it's unlikely that Macromedia will support them in future versions.

Now you need to grab the open source Remoting Gateway implementation from the amfphp crew over at http://www.amfphp.org/. Also, send them an email to thank them for their great work. That's required. If you don't do it, the Flash Gods will know and none of your scripts will execute properly ;)

This tutorial will assume you extract the files in the manner described here as the paths to various files are important so please be sure you have the following directory structure, or adjust the example code given to match the structure you choose. Your HTML document root (under IIS it's the "C:\Inetpub\wwwroot\" directory, under Apache it's generally "C:\Program Files\Apache Group\Apache\htdocs\" or similar) shall be referred to herein as 'document root'. The amfphp archive contains a single directory called 'amfphp'. Extract the archive such that the amfphp directory sits immediately below your document root. E.g. "C:\Inetpub\wwwroot\amfphp\" or "C:\Program Files\Apache Group\Apache\htdocs\amfphp\". If you've extracted the files correctly you should be able to access the amfphp gateway.php via http://localhost/amfphp/gateway.php. Try this now. You should get a prompt to download a file, like so:

That's perfectly normal, since amfphp sends back binary data, which browsers will try to download instead of displaying. If you get an error instead, please check you've observed the structure stated above and post on the forums if you continue to experience problems.

With that all out of the way, you're ready to start coding, but first, some more background information.


Page 2 of 3

A Stepwise Process
Here's a brief outline of how we can communicate directly between Flash and PHP Remoting. Each of these aspects will be covered in more detail later in the tutorial, but it's good to have an overall view of where you're headed before you start.
To send a message between Flash and PHP (let's say we're going to call a PHP function for this example), a number of steps are required. Before we can do anything we need to create a local 'Service' object in our Flash movie. When creating this object, we supply the location of the gateway.php file as well as the name of the remote service we want to have direct access to. This object only needs to be created once.
Once the service object is created, we invoke an RPC on the Service and await the results. It's important to note that (like pretty much every other communication method in Flash) Remoting is not synchronous - that means when you call your service you can't expect to get a result returned immediately, nor will Flash wait for a result before continuing to execute any other actions appearing after your call. For this reason we are provided with a means of making 'responders', which are basically event handlers which handle returned data, but more on that later.

For our Bulletin Board example, when posting a new entry to the board we will send some basic user details such as name and email and the body of the message. When retrieving posts from the board we will send back the same details from PHP to Flash. This could (and has, many times) all be done without Remoting, but Remoting makes the whole process more tightly linked (or tightly-coupled) and easier. Remember, this tutorial is just an indication of the power of Remoting, made for beginners, so don't expect to finish up with a ground-breaking application. That's for you to develop on your own :)

Under the Hood:
So far I've made amfphp sound like some magical system which manages absolutely everything for you; all you do is shift data around and the rest sorts itself out. Understanding what's going on behind the scenes is really important for development purposes, so here's a brief outline. When you send data through the amfphp gateway, it is analyzed (deserialized) and manipulated into a compatible data format for PHP, allowing you to read it in PHP as though it were native data. When you go to send data back from PHP to Flash the same process occurs but in reverse; the PHP data types are converted (serialized) to similar Flash data types. Note the keyword in that sentence was 'similar'.
Flash and PHP are both Object Oriented languages but they aren't identical in terms of the way they treat data types, (the saying goes "The great thing about standards is there's so many to choose from"). For our purposes the best example of this is the Object example. An Object in Flash doesn't translate directly to an Object in PHP, even using the magic PHP Remoting gateway. The nearest relative to a Flash Object in PHP is what is called an 'associative array', that is, an array with elements that are accessed via 'keys' (or alphanumerical names) as opposed to indexes (numbers). See the arrays tutorial for more on associative arrays. So when you see me passing Objects into PHP then working with associative arrays inside PHP, you'll understand why.

Get Started Already!
OK enough definitions, descriptions and introductions, let's get into some coding. First we're going to discuss the basics of establishing connections via Remoting and calling functions. Grab this simple example archive and place the talkback.php file into the amfphp/services directory. The services directory is a special directory where you put Flash-enabled php services.

Now open the 'talkback.php' file, the contents of which look something like this:

[php]<?php
// Create new service for PHP Remoting as Class
class talkback
{
function talkback ()
{
// Define the methodTable for this class in the constructor
$this->methodTable = array(
"returnString" => array(
"description" => "Return a String",
"access" => "remote"
),
"returnNumber" => array(
"description" => "Return a Number",
"access" => "remote"
),
"returnArray" => array(
"description" => "Return an Array",
"access" => "remote"
)
);
}

function returnString ($in) {
return "You said '$in' and I totally agree!";
}

function returnNumber ($in) {
return $in * 10;
}

function returnArray ($in) {
$objVal = $in['foo'];
return array("theKey" => "Your Object contained the value $objVal");
}
}
?>[/php]

PHP Remoting is class-based, so if you don't currently write Object Oriented PHP you'd better start if you want to make use of this new service. Each class you create can be accessed as a 'service' within Flash, and each class's methods become functions you can invoke via that service using remote procedure calls (RPCs).

In brief, here's what this file does. First it declares a new class which will be the 'service' we wish to access from Flash. Next we define the 'constructor' for this class (which is the function that is run automatically whenever a new object is instantiated from this class). The constructor has to have the same name as the class. It must establish the associative array known as the methodTable which lists information about each and every method of a class. Importantly, it tells which of these methods can be called from Flash (what you see as 'access' => 'remote'). If access is not set to remote, amfphp will refuse to run the method remotely for security reasons.

The names of the methods are pretty indicative of what they do. The returnString and returnNumber methods each take one argument; a String and Number respectively. The returnArray method takes a Flash-style Object (which as I've mentioned, is equivalent to a PHP associative array), and returns an associative array, which Flash reads in as an Object. But don't take my word for it. Let's see this baby in action!

Leave the 'services' subdirectory and open up the talk.fla file provided. Click on the first frame and double-check that the first line which points to your gateway.php is correct (if you've followed the instructions, this should be http://localhost/amfphp/gateway.php). This file contains configuration options, like the character set you want to use or the location of the services directory. It also gets the amfphp machinery going. With amfphp, you don't point to the services directly; you always talk to your services through the gateway.

Don't look at the rest of the code yet, just test run the movie. If you're setup correctly, your trace window should output the following:

[code]Calling returnString
Calling returnNumber
Calling returnArray
Got result "You said 'Flash Remoting is groovy' and I totally agree!" of type string
Got result "500" of type number
Got result "[object Object]" of type object which contained the following:
theKey: Your Object contained the value bar[/code]

If you look back at the 'talkback.php' file you'll get an idea of what's going on. We're passing values to the PHP methods and they are returning them, then they are being traced out to the output window.
Now we'll dig up a very useful tool called the NetConnection debugger. The NetConnection debugger is located on Windows at C:\Documents and Settings\{Your username}\Local Settings\Application Data\Macromedia\Flash {version}\{language}\configuration\WindowSWF\NetConnection Debugger.swf. On OS X it should be in: /Users/{username}/Library/Application Support/Macromedia/Flash {version}/{language}/Configuration/WindowSWF\NetConnection Debugger.swf. Since it's a very useful tool, you'll probably want to make a shortcut on your desktop to it so you'll have it handy whenever you need it.
Close the test movie, and double-click on the NetConnection Debugger.swf file to open it. You should get a new window which pops up. Now test 'talk.fla' (Ctrl+Enter) again but this time, ignore the output window (the output is the same) and take a look at the NetConnection Debugger. This window lists communication between Flash and the installed Remoting service. If everything is going well you should see eight entries in the 'Events' listing at the left; one Connect, three Calls, another Connect and three Results. You can click on any event listed and click the Details tab to see everything that's happening; have a look around.
This is what's going on behind the scenes to cause that output we saw a moment ago. The first connection indicates the request made by Flash to create a Remoting service. Each Call represents a Remote Procedure Call (RPC) and each Result indicates a value being returned from the method which was called via the corresponding RPC. The second connection is triggered when amfphp asks Flash to call another gateway in the future, one which has the session id appended to the URL; this allows you to use sessions without cookies. You'll see that we call the three Methods available in the talkback.php file in the order they are written, and the results come back in that same order. Note that the Calls and Results are grouped together, not mixed up. This illustrates what I was saying before about Flash Remoting being asynchronous; the requests are sent one after the other, without waiting for a result to be returned. So how am I tracing the results as they come in? I'm glad you asked that, let's take a look at the code.

Close the test movie so that you're back to the talk.fla and view the actions on the first frame. Let's go through these actions together.

First we define the gateway url. Next we include import a few ActionScript packages which come with the Flash Remoting Components you installed earlier. To be able to use these packages, I had to place the classes in the library. This is a very important step that people tend to forget. To put the classes in your library in your next Remoting movie, in Flash 8, click Window > Common Libraries > Remoting, or in Flash MX 2004, click Window > Other Panels > Common Libraries. Then drag the 'RemotingClasses' and 'RemotingDebugClasses' symbols on the stage of your movie. You can then safely delete them, they will stay in your library from now on.

mx.remoting.* defines most of the groovy classes we use in Flash Remoting like Service and RecordSet. mx.remoting.debug.* is what makes the NetConnection debugger run. mx.rpc.* contains helper classes like PendingCall and ResultEvent (more on these later). These three lines should be the first things you type in all your Flash Remoting projects. Right after we start the NetConnection Debugger with NetDebug.initialize().

Note: It's been brought to my attention that different versions of the NetServices.as file have different capitalization of the setDefaultGatewayURL string. E.g. setDefaultGatewayURL vs setDefaultGatewayUrl. Since ActionScript.org 2.0 and above are case sensitive, you will need to ensure you are using the right one. You'll get an error if you're not, saying the function doesn't exist.

[as]//Set this to the location of your gateway.php file
var gatewayUrl:String = "http://flashservices/gateway.php";

// Import packages necessary for Remoting debugging and coding
// Note that the Remoting components must be in the library for this to work
import mx.remoting.*;
import mx.remoting.debug.*;
import mx.rpc.*;

//Start the NetConnection debugger
NetDebug.initialize();[/as]

Next we define the location of our gateway and establish a Service between Flash and our gateway via HTTP, which is why you need an active web server to test this stuff locally. We need only do this once and the Service will be available until the movie is unloaded. When you want to invoke a method in one of your classes you send a message through the Service ('down the phone line' if you will) and your PHP class executes and sends any response back via the same phone line. The Service class constructor takes three arguments, the gateway url, a seldom used second parameter (usually null), and then the service name.

[as]//Set this to the name of the remote service
var serviceName:String = 'talkback';

// Create PHP Remoting Service
var talkback:Service = new Service(gatewayUrl, null, serviceName);[/as]

PHP Remoting looks for a file in the services folder with the same name as the service we request. For instance, in this example, our class is called 'talkback' so it is saved in talkback.php and we request the service called 'talkback' via Flash. If the class is named differently from the file, amfphp won't be able to find it. I also name the reference to the service 'talkback' so that when I invoke methods it's obvious which class I'm talking to.

With the service established we can now invoke methods as though the service were a local Object "talkback.methodName();". Before calling the remote methods, we need to define callbacks so Flash will have something to do with any results which are sent back from that method invocation. What we do is create result functions and fault functions. The result functions are called when a Remoting call works; it always take one argument, the ResultEvent. Inside this object's 'result' lies the result of the remote function. Inside this function we define the actions we want to take place when results are returned from a remote method.

We also define fault functions. Fault functions are called when the remote method ran into a snag; for example, when the remote method doesn't exist or we don't have the permissions required to call it. Fault functions take one argument, the FaultEvent. Inside this object is a 'fault' object which itself contains the all important 'faultstring'. You don't *need* to create fault functions, but I included it here for completeness. You can see faults in NetConnection Debugger anyway.

The next few function definitions inside talk.fla are called 'handleSomething' with a name related to the remote function and tell Flash what to do with results sent back from each of those methods.

[as]// Define result handling code
function handleSimpleReturn(re:ResultEvent) {
trace("Got result \""+re.result+"\" of type "+typeof (re.result));
}
function handleArrayReturn(re:ResultEvent) {
trace("Got result \""+re.result+"\" of type "+typeof (re.result));
trace("It contained theKey: "+re.result.theKey);
}
function handleFault(fe:FaultEvent)
{
trace("There was this fault: " + fe.fault.faultstring);
}[/as]

Finally, we call the methods via the service reference we defined within Flash and await the results.

[as]// Call some functions
trace("Calling returnString");
var pc:PendingCall = talkback.returnString("Flash Remoting is groovy");
pc.responder = new RelayResponder(this, 'handleSimpleReturn', 'handleFault');
trace("Calling returnNumber");
var pc:PendingCall = talkback.returnNumber(50);
pc.responder = new RelayResponder(this, 'handleSimpleReturn', 'handleFault');
trace("Calling returnArray");
test = new Object();
test.foo = "bar";
var pc:PendingCall = talkback.returnArray(test);
pc.responder = new RelayResponder(this, 'handleArrayReturn', 'handleFault');[/as]

As I mentioned earlier, service calls are asynchronous, which means you won't get the results straight away. What you get instead is a PendingCall. The PendingCall contains a responder which you must fill in with a RelayResponder. The RelayResponder takes three arguments: the first is the scope in which your callbacks are defined (in this case, this, or _root), the second is the result function, and the third is the fault function. So basically to call a remote method you need two lines of code, one for the actual call, and another to define the responders. Not too bad.

This may all seem a bit much but it's really quite a simple (and pointless) application. Take a moment to read over it again and fiddle with the source file to get your bearings before we continue with a more useful and slightly more challenging example.


Page 3 of 3

Building the Bulletin Board
You're going to need the source files for this section of the tutorial as we're not going to build this application from the ground up; rather we'll deconstruct a completed version together, allowing you to see how the system works. The Bulletin Board, as I've implemented it, uses a MySQL database with the structure as shown below. If you don't understand what it means, don't worry, this structure is really just useful for anyone who actually wants to implement this system, which you are free to do, commercially or non-commercially, so long as you credit me :)

[code]CREATE TABLE posts (
id tinyint(4) NOT NULL auto_increment,
name varchar(100) NOT NULL default '',
email varchar(100) NOT NULL default '',
url varchar(100) default NULL,
message text NOT NULL,
date datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (id)
) TYPE=MyISAM;[/code]

Place the BulletinBoard.php file in the services folder. Now open up BulletinBoard.php and have a look. This file is used to read existing entries to and create new entries to the board on the backend. It contains the class definition, the constructor, the doPost and doRead remote methods as well as a helper 'escape' method.

Recall that the power of remoting is allowing Flash to connect to classes and reference methods therein as local methods. This means that when we connect to the BulletinBoard class within Flash we get access to the doPost and doRead methods of that class from Flash.
The constructor method, as with our simple example above defines the methodTable which lists information about all methods in this class (in this case the doPost and doRead methods). We connect to the database immediately inside the constructor since we are going to need a MySQL connections for all of our remote methods anyway. The constructor is a good place to initialize variables, create connections and similar tasks, in addition to being the place where the methodTable is defined.

The doPost method takes in an associative array (Object passed from Flash) and pumps the information in that array into the database, returning a simple 'success' or 'fail' message (in the form of an associative array) for debugging at the other end.

The doRead method takes two arguments which are used in retrieving results from the database rather than pumping information into it. Notice that we are simply returning the result directly from mysql_query. In Flash we will receive this result as an instance of mx.remoting.RecordSet. That RecordSet will then have methods like getItemAt, filter, sortItemsBy and all sorts of useful things. The RecordSet object can then be bound to the v2 components like the DataGrid component or the ComboBox and viewed as is. Sure beats XML, doesn't it ? (remember xml.firstChild.childNodes[i].nodeValue?)

What's really happening behind the scenes is that amfphp detects the returned result and loads an appropriate driver for it. This driver is written specifically for the database system we are using. amfphp recognizes MySQL, PostgreSQL, Oracle, PEAR::DB, SQLite, and whole bunch of other database types automatically. Then it encodes it in AMF using a special format and sends it back to Flash, which maps it to mx.remoting.RecordSet. amfphp's database drivers are optimized for speed, so if you need to send back large amounts of complicated data, send it directly as a RecordSet for a nice speed boost (it's simpler anyway).

Note also the NetDebug::trace statements in both the doRead and doPost methods. In Flash, you can use the trace statements to view things in the trace window. With amfphp, you can achieve a similar result with NetDebug::trace. You will get a new line in the NetConnection debugger called 'Trace' with an icon that looks like two tin cans along with the results of the remote call. By clicking on it you will see the contents of the trace stack. NetDebug::trace can be used to send back strings, like trace, and also objects and arrays. Here I'm tracing the SQL strings so if they are malformed I'll know it immediately. It's also very useful to trace mysql_error to get debug info in case your SQL is wrong. Of course you wouldn't want to deploy your app and still have SQL showing up for everyone to see! You can open up the gateway.php file and set PRODUCTION_SERVER to true to disable remote tracing; this is similar to the 'Omit trace' checkbox in the Flash Publish settings.

Finally we have an escape method which simply escapes an argument (add slashes before the quotes). This is a private local method so it's not defined in the methodTable. PHP comes with a feature called 'magic quotes' which escapes quotes (') so you can insert variables with quotes in them in a database directly. amfphp does not enforce magic quotes (it acts as though magic quotes were off), so it's important to escape data before putting it in the database, otherwise names like O'Conor and D'Alembert will cause an error.

Now let's look at the ActionScript. The BulletinBoard.fla file contains only one line of ActionScript; the rest of the code is in BulletinBoard.as. This ActionScript file may look a little daunting at 280 lines of code, but it's mostly comments and whitespace so don't despair. The bulk of the code is similar to the simple example given above so that little explanation is warranted. First we import the ActionScript packages for successful Service establishment and debugging. In the init method, we define and connect to our Service. Right below we define local functions which call the corresponding remote methods, and right below those we write the result handlers. Pretty simple huh? You can figure what each method does by looking at the prefix: 'do' call remote methods, 'handle' receives remote results, and 'on' handles UI events. Below the interesting Remoting stuff there's a lot of boring UI code, which you should have probably become accustomed to by now.

Let's look at the doPost method. All it does is take an info object and passes it along to Remoting. This info object is created by the onPost method. It combines the values of the text field into an object and then just passes that object to the doPost method of the service object, which is of course just a link to our external MessageBoard.php file, so the message object we establish is piped through to the PHP file which reads out the values and stores them in our database. See how simple and brilliant it is? No need to convert the data to strings and then back at the other end, no need to serialize the data. No work period. Just pass and smile. If you take a proper look at the handleDoPost method you'll see that all it does is hide the post interface and refreshes the main datagrid.

(At this point I should say that I feel this tutorial is a major divergence from the standard slow and stepwise approach I take to teaching ActionScript in all my other content. Comments on how well you understood this tutorial - after you've read it all of course - would be much appreciated.)

Now for the really interesting part. Take a look at the doRead method. What it does is simply call the remote function and gets back a RecordSet with 10 items. In handleDoRead, all we do is set the dataProvider of the DataGrid to the returned RecordSet. That's all we need to do to show our data. That's right... All that cool functionality, the DataGrid with the headers, the draggable columns, the clickable rows, the sortable data... That's one line of code. (Did I mention I love Flash Remoting?) In the initUI method I had prepared the columns of the DataGrid. The column names are the same as the name of the SQL table columns.

Here I've only shown three of the 6 columns amfphp sent back. The rest of data is not shown, but it's still stored in the datagrid's dataProvider. I set up a listener for the datagrid's change event, the onDgChange method. What it does is inspect the hidden data for the currently selected row and fills in the TextArea below with all of the data. Again the names of the data keys is inherited from the names of the SQL table columns.

So that's it folks; my longwinded and rushed introduction to Flash MX Remoting (using PHP). Over 5000 words; that's my record I think. Take a look at the amfphp documentation for more info, especially on how to debug your services. As always, please post questions related to this topic or this tutorial on the relevant board (try the Flash Remoting board!) in the Forums section of the site for assistance. Comments and error corrections regarding this tutorial are welcome. Have a great day!

Jesse Stratford [email:[email protected]] is the Co-Master of ActionScript.org and a freelance Flash developer and teacher. He is based in Australia and enjoys all things Flash.

NB: If you have comments or feedback please feel free to email me, but please do not email me Flash questions; the forums are provided for that purpose and you will get a faster answer by posting you question there.

If you have found this tutorial helpful, I hope that you will take 30 seconds to visit The Hunger Site where, with just one click you can make a free donation of food to a starving person in a third-world country. We do not benefit financially from this action; it is purely an act of charity.
This tutorial is protected by International Intellectual Property Rights laws and may not be reproduced or redistributed in full or part, without the prior written consent of the author. Unauthorized reproduction of this tutorial or its contents may result in prosecution. I've worked hard on this tutorial, please don't steal it.