SWX: SWF Data Format

Icon

SWX is the native data format for Adobe Flash. This blog is about all things SWX, SWX RPC, SWX PHP and the SWX APIs (Flickr, Twitter, etc.)

SWX ActionScript Library: using the prepare() method of the SWX class

When working with SWX RPC, you don't want to continuously serialize complex arguments by hand when call server-side methods. And you don't have to, if you use the prepare() method of the SWX class in the SWX ActionScript Library that comes with SWX PHP.

Save your FLA in the flash/ folder (the one that has the org and com folders) before continuing. (Or add that folder to your ActionScript classpath in the Flash IDE and save your FLA anywhere.)

Modify the code sample so that it matches the listing below:

import org.swxformat.SWX;
 
dataHolder.serviceClass = "Calculator";
dataHolder.method = "addNumbers";
dataHolder.args = [35, 7];
dataHolder.debug = true;
 
SWX.prepare(dataHolder);
 
dataHolder.loadMovie("http://localhost:8888/php/swx.php", "GET");
 
function onEnterFrame()
{
    status.text = dataHolder.result;
}

The prepare() static method of the SWX class simply serializes your arguments into JSON format for you. Notice that the args property in your dataHolder is no longer a string but an ActionScript array with two numbers inside it.

This is definitely far better than manually serializing your arguments by hand but it's still not ideal, is it? For one thing, that onEnterFrame function we're using is not a good practice. It would be really nice if we could have an event handler called when the data arrives instead of polling for it. The SWX ActionScript Library provides that functionality for you too.

Calling SWX PHP methods from Flash

You've verified that your server-side service method is working correctly by using the SWX Service Explorer. Now let’s call this method from Flash.

  1. Open up Flash and create a new FLA (ActionScript 2). You can set the publish setting to Flash 7 or 8.
  2. On Frame 1 of the new FLA, create a movie clip instance and give it the instance name dataHolder.
  3. Create a new layer and call it Actions. On the Actions layer, add the following code:
dataHolder.serviceClass = "Calculator";
dataHolder.method = "addNumbers";
dataHolder.args = "[35, 7]";
dataHolder.debug = true;
 
dataHolder.loadMovie("http://localhost:8888/php/swx.php", "GET");

That's it! That's all the code you need to call the addNumbers method on the Calculator service class in PHP and pass it the numbers 35 and 7 as arguments. The loadMovie calls the SWX gateway and passes to it any of the properties you set on your movie clip. In this case, since we are sending a small number of arguments, we use the GET HTTP encoding method. We could just as easily have used POST.