Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. Workflow

Using AMFPHP with AS3 and CodeIgniter


It seems that the AMFPHP project has now been laid to rest, unfortunately it never made it past the 1.9 beta version and nor did the tutorials. However, Adobe didn't give up on it that easily and with the new Flex compilers they've included the AMF3 object encoding!

Good news for all you Flexers, but it's a different story for all you AS3'ers. Flex allows you to quickly and simply build a service that will interact with your AMFPHP code, but you have to get your hands dirty with AS3. So, I've decided that it's time there's a decent set of classes out there that help Bob build a site with AS3 using the AMFPHP gateway.

And to throw some more dirt into the mix, we'll be integrating AMFPHP with CodeIgniter so that we have a fantastic PHP framework for the backend.

As you can see there's not much to look at, but in fact it's the basis for our Flash communication classes; we can simply and easily send and receive data objects between the client side and the server side without serialisation.

Before we start...

It's a logical idea that you've had a good delve with ActionScript and PHP. You don't necessarily have to know how to use CodeIgniter as you could just use a PHP class as a service, but it's worth knowing PHP.

Step 1: Why Use AMFPHP?

This question gets thrown around a lot. We know that flash can get data from XML, JSON, etc... But AMFPHP uses a different form of encoding called "Action Message Format". It's simply sending binary data rather than ASCII. Now there's lots of blog posts around comparing XML, JSON and AMF, but at the end of the day AMF has these great advantages:

  • You don't need to serialise any data! For example, if you're passing some objects from PHP to Flash, you need to serialise them as, say, JSON. Flash will then have to parse them in order for them to be usable, this takes time and memory.
  • It's lighter than XML because you're never duplicating yourself. For example, in XML you have to start with a root tag, then more tags, then closing tags, so you'll see yourself duplicating tag names and this takes up bandwidth. Further more, XML, just like JSON, needs to be parsed into E4X and this takes time.
  • AMF can be fully integrated with your PHP code meaning that you can write less code. I'll show you this by using CodeIgniter as well as AMF's standard services.

Remember, AMF isn't a replacement for XML or JSON, it's simply another tool in your arsenal when it comes to developing scalable dynamic applications.

Step 2: The Set Up

Fire up your favourite IDE, whether it's Flex Builder, FDT, FlashDevelop or TextMate and create a new ActionScript project. In addition to this, we'll be doing some PHP coding too, so get your PHP IDE ready (I recommend Aptana)

Additionally, we're going to be using GreenSock's TweenLite class just to give the application a bit of magic.

For those of you who've read my recent articles: we're not going to be delving into PureMVC this time as I wanted the outcome of this article to be a set of classes that you can reuse again, with or without PureMVC.

Step 3: Creating the Base App

Just like with any ActionScript app, we need to set up our base app. I'm just going to start by just creating a simple background for the app, then we're going to look at creating the text area for the response and buttons to send a string, array, and object to PHP; so create a new file called "App.as" within "src/":

Step 4: Creating the UI

Since we're going to need some sort of UI for the user to be able to interact with our app, we're going to have to code one! Now it's up to you whether you want to create your UI in the Flash IDE (or the new Flash Catalyst IDE, looks nice) but I'm going to be hardcore and code it..

In terms of UI components, we're after:

  • An input text box
  • A button
  • A text area

It's just the start to your UI classes, but these are all we're going to need at the moment.

Step 5: Creating an Input Text Box

Since I believe that re-writing code is just long and unnecessary, let's create a reusable UI button component. Create a new file called "InputTextField.as" within "src/com/flashtuts/lib/display/ui" and use the following code within it:

Now, let's quickly go through it. We start with our constructor, we construct our two main variables: the background 'bg' and the textfield 'field' then we add them to the stage:

Our class relies on the user using the public function "init()" that will draw the background as well as setting up the text field:

Then finally we want to be able to set some text (if we need to) and to get any text that the user has entered, so we use get/set functions:

You can see that you're able to set an ample number of variables. You can always come back and change this, but for the time being it works for this tutorial, so let's continue.

We now want to add this field to our application, so I've created a new function called "addTextField()", and called it within "init()", so our app's code looks like this:

You can see that within the function I've created a new text format and passed that, with other parameters too, to our "InputTextField()" class. Fire up a preview and you'll see your text field in the top left hand corner. Before we position anything, let's finish the other UI components.

Step 6: Creating a Button

Now that we have our input text area down, let's create a button that'll allow us to push the data we enter to AMFPHP. So create file called "Button.as" inside "src/com/flashtuts/lib/display/ui/" and use the following code:

A quick run through: much like our "InputTextField()" class, we construct our two variables 'bg' and 'field' and also set properties so that this class acts as a button:

Again, just like our "InputTextField()" class, we set up the display of the class:

Finally we need to adjust our app's base class like so:

If you ran this in debug you'd see a button over a text field, so nearly there!

Step 7: Create a Text Area

This one won't be so hard as we've done the hard work in the "InputTextField()" class already, so all we'll need to do is set the height and width of our textarea, a simple enough copy and paste job. So create a new file called "InputTextArea.as" inside "src/com/flashtuts/lib/display/ui/" and use the following code:

I think at this point there's no need to explain the whole class, but it's worth mentioning the configuration of the field that allows it to become a text area. We simply added two more properties and set them to true: 'multiline' and 'wordwrap'. These turn the input box into a text area.

So finally, let's add the last component to the app's class:

Finally, let's just align our UI so it's usable and set the 'textField' and 'textInput' so that they're class wide functions rather than within the "addTextField()" function:

So that's our base class pretty much finished. Now we'll move on to writing the classes for AMFPHP communication.

Step 8: Starting With the Basics

I'm assuming that you've worked with loading data into Flash player before. When working with static data that's normally loaded right at the start of your application being loaded, using XML or JSON is fine. It's also fine with dynamic data, but AMF gives you the advantage of a constant gateway, good performance and, most importantly, less code to write as there's no need encode or decode the data.

What normally happens when working with data and Flash is you'd normally either load a static file or have XML or JSON dynamically created, for example:

It's all fair and well loading data, but what if you want to send data? Yep you can of course set up a few classes to send data to your site's dynamic scripts but then you'll already have set up a class for retrieving data and then you'll have to modify it so that it'll allow you to send data. Plus of course, you'll need to update your dynamic scripts on your site's servers. Now this is where AMFPHP is so great, you only need to create one set of classes for ActionScript and then all your PHP code can be contained within one simple code base. I'll also extend it to show you how you can use a framework, in this case CodeIgniter.

Step 9: Creating the ActionScript Classes

Since AMFPHP is a remote connection service, you may want to create other classes in the future, besides what's the point of duplicating code? What we'll do is create three classes:

  • "RemoteConnectionService.as": this will act as our base class and will have useful functions that we can use in the future for other remote connection services
  • "RemoteConnectionServiceEvent.as": this will act as the events class that the base class will use
  • "AMFPHPService.as": and this will be our AMFPHP connection class

This way we'll be able to create a nice set of classes but also have them clean and scalable should we need to write some new ones in the future.

Step 10: Creating the Base Class

First thing we'll do is start with the base class. So create a file called "RemoteConnectionService.as" within "src/com/flashtuts/lib/data/" and it'll extend the "NetConnection" class:

Now we've got our class, we need to write some code, so we've got to think what functions can be placed within the base rather than be duplicated. I would suggest using the constructor to set up the connection, then using the base to handle any events the connection sends and finally we create a standard function that we will use to send our data.

The first thing to do is to write our constructor:

Now you may be wondering what on earth all that is, not to fear, here's a quick run down:

  • The public vars:
    Since this class is going to act like a service we need to tell it where the AMFPHP gateway is, therefore we set the 'gatewayURL', furthermore in order to have result and fault listeners we have to create a new "Responder()" (you may be wondering why this isn't through events, maybe Adobe were hungover that day) and we will bind this responder to our calls. Finally it's always handy to have the ability to store the data we receive from our transactions in an accessible public var, in this case called 'data'.
  • The private vars and 'handleReady' var:
    Now since this is the base class for our remote connection service, there may be times when you'll want to manipulate the data before it's sent back to your application. Therefore instead of just having a 'ready' event fired, I've set a 'loaded' event too. This will allow you to hook into the service, manipulate the data and then dispatch the 'ready' event. By default, any subclasses will define these events as part of the 'RemoteConnectionServiceEvent()' class, but we have the ability, when super-ing, to say otherwise, allowing for greater flexibility.

When we construct the class, remember this is a base class so it'll always be super-ed rather than constructed itself, we pass in the 'gatewayURL', the events, and the encoding value (this defaults to '3' which is AMF3 style encoding, perfect for us).

Step 11: Handling the Responses and Event

Now we need to create the event and responder handlers for this class, so let's add them:

Here you see that we've added the responder functions "handleResponseResult()" and "handleResponseFault()". Also, we have the "handleNetEvent()" just incase anything falls on it's face and finally we have the "handleLoaderDataReady()" that will be called once the data is ready - instead of any hooks you may want to use.

You can see that it's always dispatching events that you're able to define. This will allow for greater flexibility and scalability in the long run.

Step 12: Creating the Events Class

Since we're dispatching events from our service base class, it makes sense to have a default events class. If you're feeling lazy and can't be bothered to create your own events class, you can just use this as we'll specify the class to use these events by default, so create a file called "RemoteConnectionServiceEvent.as" inside "src/com/flashtuts/lib/events/":

It's a pretty basic events class, we're extending the standard "Event()" class and adding our own public var called 'data' so that we can send data with the event and easily retrieve it through our listeners.

Step 13: Creating the AMFPHP Class

Now our base class and it's events class are ready, all we need to do is extend the base so that we can use it for our AMFPHP service class. Create a new file called "AMFPHPService.as" inside "src/com/flashtuts/lib/data/":

Don't be confused, it'll all make sense in a few paragraphs time, let's start with the constructor: like I've said further up, our base class will always be super-ed, so within the constructor we pass the 'url' variable given to this class when it's constructed as well as the events and finally the default encoding. The reason I'm choosing to separate the "AMFPHPService()" class from the "RemoteConnectionService()" class is because it'll allow for greater flexibility and scalability, as you can write other services that will take advantage of the base, but have different events and functions.

Before we continue, it's worth talking these special variables called ...(rest) which basically means that a function can accept any number of comma-delimited arguments, for example:

Traditionally you'd need to declare a function's arguments like this:

However with ...(rest) arguments you can do this:

And call it like this:

So you can use any number of variables. These are then accessible in the function as an array, for example:

"NetConnection.call()" takes advantage of these ...(rest) arguments allowing you to send any number of arguments to your gateway. However, the function also requires you to give the 'responder', something that we created within our "RemoteConnectionService()" class. So since we're always going to need to use this "call()" function but don't want to write the 'responder' variable every time we use it, we should put it within our base class. Go ahead and open up the "RemoteConnectionService()" class then update it with this:

Step 14: Tying it in

Now that our service classes are ready, if we go back to our app's base class we have to add the service by creating it as a class-wide variable and constructing it within our "init()" function:

And since we're going to be using the service when the user hits the button, we need to add the event listeners to the buttons and then set up the function that will run our service's "send()" function to make the call:

You'll see that we're using a method called 'HelloWorld.say', this is a test AMFPHP service and I'll show you how to create your own later. And finally we need to add listeners to the service so that we can handle the ready event and display the response in the text area:

That's our ActionScript classes done! Now on to some PHP!

Step 15: Using AMFPHP

The first thing to do is to go to the AMFPHP web site and download yourself a copy of the code base. Once you've got it, uncompress it and stick it on your testing server or run it on your localhost. If you're new to PHP, it's worth reading up on it at w3schools.com.

Once you're happy that you know enough about PHP, it's time to get your hands dirty! The idea behind AMFPHP is that you can create a set of services and call them much like how you import files in ActionScript, for example:

AMFPHP comes with a standard service called 'HelloWorld.say'. The class and file are called 'HelloWorld' and the function is called 'say'. AMFPHP goes to the services folder, finds a file called 'HelloWorld.php', constructs the class called 'HelloWorld' and then runs the function called 'say'. If you were to have a class called 'Test' that belonged to the 'com.flashtuts' code base, so you created a file called 'Test.php' inside the folders 'com/flashtuts/' then you would reference the service like 'com.flashtuts.Test.function'. Simple eh?

The first thing we're going to do is just get our PHP class to return a simple string and then we'll move on to integrating CodeIgniter.

Step 16: Saying Hello Back

Since we've defaulted the text in our input field to say 'Hello', we may as well say something back, so create a new file called "HelloWorld.php" inside the "services" folder in your AMFPHP folder and use the following class:

Now if you fire up your application you'll see that the server will return 'You said: (whatever you said, probably hello!)' in the text area, without the bracket bit at the end. Yay, you've used AMFPHP, good work! Let's get a bit deeper.

Step 17: Using a Database

We've returned what we sent to the server, but who wants that eh? Surely we'd want to store something in the database right? So, let's sort that out. Open up the file "globals.php" in the AMFPHP base directory and you'll see a bit of code that's commented out like this:

You can either copy this and paste it underneath or just uncomment it, we'll be using it to set our DB access. So enter your DB username, password and database, so it looks like this:

Now we're ready to alter our PHP class, so load up the "HelloWorld.php" service class and paste the following inside:

Here's a quick run through:

  • We create a class wide variable called $db, we'll use this to store our database connection so that we won't need to reconnect within our functions
  • The "__construct()" function sets up the database connection for us
  • The "put()" function inserts the string $data into a table called 'hello_world' within our database

Cool yea? let's try it out. Change the method in your ActionScript app to 'HelloWorld.put', fire up the debug and have a go. Then use your SQL browser or phpMyAdmin to check the results in your database. You should see the insert id returned in your text area.

Step 18: Tying in CodeIgniter

Now stopping with the above is fine, you can go ahead and make a few classes and functions that will suit your site's needs, but what if you have bigger aspirations? We all know that building apps can be faster when using frameworks and CodeIgniter is a great framework. I don't want to get into the argument of which framework to use because at the end of the day CodeIgniter works for me for a few simple reasons:

  • It's lightweight
  • It's simple to install
  • It's easy to learn
  • It's got good community support
  • And it's free!

There are other frameworks out there, but for this tut I'm going to show you how you can hook CodeIgniter into the AMFPHP platform.

Step 19: Installing CodeIgniter

Grab yourself a copy of CodeIgniter from their site, decompresss it and stick it up on your server or localhost. It's pretty simple to install but for the time being we don't need to set up a database or anything like that. For future reference, have a read of their user guide. So if you then load up your browser and point it towards where you've put CodeIgniter you'll see something like this:

Step 20: Creating the Hook

Ok, now we need to modify CodeIgniter's output by using a hook. A hook is simply a method that allows us to 'hook' into the core of the system without directly editing CodeIgniter's code. So we need to edit CodeIgniter's config so that we can enable hooks, register our hook and then write our hook. Within your CodeIgniter directory open up "system/application/config/config.php", scroll down to line 91 and change the variable to true:

Now open up "hooks.php" in the same folder and add the following code before the '/* End of file ... */' line (so add it to line 13):

What we're telling CodeIgniter here is that we want it to override it's display output method and instead re-route everything to our hook class called 'AMFPHP' within the 'hooks/amfphp.php' file. Since that fine doesn't exist, create the file "system/application/hooks/amfphp.php" and use the following code:

All we're doing here is telling CodeIgniter to write its output. This way we're controlling the system by checking to see we're not making a request via AMFPHP so it can display the code as normal, otherwise AMFPHP won't work.

Step 21: Creating the Controller

Ok we're nearly there, all we have to do now is create our controller so that we can return the data back to the AMFPHP gateway. Create a file called "system/application/controllers/main.php" and paste this in the file:

All we're going to do here is just return the variables we sent to AMFPHP as an array rather than as the string we sent. This will show you how magic AMFPHP is, the fact that you don't need to serialise objects before sending them back and forth is a great asset and speeds things up.

Step 22: Configuring AMFPHP

We're really nearly there! We now need to create a service that will invoke the CodeIgniter framework. This service will act in the same way as the "HelloWorld.php" service we created, but will instead fire up CodeIgniter so that we can access all of it's goodness. Create a new file inside your AMFPHP directory "services/CI.php" and paste in the following code:

We define a function called "execute()" where we will pass the URL of our 'spoof' CodeIgniter method (if you're confused, it works on the basic principle of MVC URLs where by the application responds to URL patterns like http://host/controller/function/value1/value2/valueN, you can find out more here: http://codeigniter.com/user_guide/general/urls.html) and the values for that method. In then requires the 'index.php' file of your CodeIgniter app, make sure it can find this by the way!

Step 23: One Last Configuration Item

You're so close! One last thing to do is to tell CodeIgniter to only explicitly show errors, so open up the "index.php" file in your CodeIgniter directory and edit line 12 to be:

We're telling PHP not to display any notice errors, only full fat ones!

And that's the PHP side down! All we need to do now is go back to our ActionScript code and change the method, so open up your app's base file and change the method and values we send like so:

Here we're sending an Array rather than a number of values. This is easier and means that you can have your gateway receive the method (as the 'URL') and the data as an Array.

There we have it! You've just dug deep into AMFPHP from both the ActionScript and PHP side! Congrats!


While some people may ask what's the point of this, there will be times within a professional developers life where he or she will need to use AMFPHP when it comes to sending and receiving data. And while XML and JSON work just fine, the beauty with AMFPHP is that when you've set up the classes (as you just have) you don't have to worry about the joys of serialising data and parsing it at the receiving end as it's all done for you!

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.