Created with Sketch. Created with Sketch.

Using amf in flex

Hi everyone!
My name is Cosmin Albulescu and this is the first time I’m posting on my blog. I’ve been working as a web developer for about 6 years, using common technologies like javascript, php, action script, or flex.

This post may be very useful for those who want to create a simple remote procedure call with amf and flex.

AMF (Action Message Format) is used in action script in order to exchange serialized data between a flash application and a remote server. To find more information about the amf please visit this link

Why using amf protocol, there are lots of advantages.

  • It is faster than usually calling a php file that returns an xml
  • It is more practical because the data is already serialized
  • iIn flex you already have classes that work with amf

The first thing that needs to be done when you want to use amf protocol is to write your server side methods and pass it to the amf protocol hanlder class. The amf handler class receives the binary call from flash or flex application, calls your service method and returns the binary serialized data back to the flash.

There are several classes that do this thing for most of all programming languages. For the php the most known are AMFPHP, SabreAMF, WebORB for PHP, Zend_Amf, php-amf3 extension.

In this example is used the Zend_Amf from the Zend Framework, a framework library written by the zend community.

Steps to build your remote service methods

STEP 1 – Create amf Service file

Create a file called phonebook.php wich holds the main service methods

class Phonebook
{
 const DATA_FILE = "phonebook.dat";

 private $phonebook;

 public function __construct()
 {
 $this->phonebook = unserialize(file_get_contents(self::DATA_FILE));
 session_start();
 }

 public function login($user, $password)
 {
 if($user == "admin" && $password == "1234")
 {
 $_SESSION['logged'] = true;
 return true;
 }

 return false;
 }

 public function sync($phonebook = null)
 {
 if(is_array($phonebook) && count($phonebook))
 {
 $this->phonebook = $phonebook;
 file_put_contents(self::DATA_FILE, serialize($this->phonebook));
 }

 return $this->phonebook;
 }
}
}

The php code above is a simple phonebook application that save your serialized array with phone numbers into a file. This is a fast method just to show how to use the amf. You may also use mysql or other saving methods. The functions of this class must be public to be accesible from flex, you cannot call the private or protected methods.

STEP 2 – Instantiate the Zend_Amf_Server for handling the service class

Now will create a file called api.php with code below wich handle our public methods. For that we need to download the Zend Amf package, a simple way for get this is to use the packageizer application This package generator pack just nedded classes from the framework.

.

    //set your include path to the zend framework
    require "Phonebook.php";
    require "Zend/Amf/Server.php";
    $server = new Zend_Amf_Server();
    $server->setClass('Phonebook');
    $response = $server->handle();
    echo $response;

This class is simple to use just instantiate the Zend_Amf_Server class and pass your class to it. The setProduction method is used for throwing or not the errors generated from Phonebook class. For more documentation about using the Zend_Amf_Server please visit documentation page. From this point your service is functionable and the public methods can be called. From now on will need to do the flex application mxml wich will use this remote file.

STEP 3 – Create flex main file

This is a simple layout  having two states one for logged and other for editing mode with a DataGrid component and buttons for add and remove item. The code below is all needed to do for flex side, create the ui and build the logic for it.

View the mxml source

The class that is used to call remote amf methods is RemoteObject, if this is used from action script make sure you have been imported from the right package. The package for doing with the action script is mx.rpc.messaging. After will done with the RemoteObject initialization we need to create the operation that are linked to server side amf methods.

private function init():void
 {
 rpc = new RemoteObject();

 var channels:ChannelSet = new ChannelSet();
 channels.addChannel( new AMFChannel("api", "api.php") );

 rpc.destination = "api";
 rpc.channelSet = channels;

 rpc_login = rpc.getOperation('Phonebook.login') as Operation;
 rpc_login.addEventListener(ResultEvent.RESULT, onLoginResponse);

 rpc_sync = rpc.getOperation('Phonebook.sync') as Operation;
 rpc_sync.addEventListener(ResultEvent.RESULT, onSyncResponse);

 addEventListener(StateChangeEvent.CURRENT_STATE_CHANGE, onStateChanged);
 }

After the RemoteObject and operation instances are created make sure you add handlers for operations that are waiting for response for example the login method will return true if user has been logged in or false if not. A important think is to create crossdomain.xml on root where api.php file is created, otherwise the remote calls will be blocked by the flash security concern. This is just in case you are using a different domain if all files are in the same path is not necessary.

Try using user admin and password 1234

This is just a demo and data will be deleted after 10 items.

Download the source file

I hope this post is usefully for flex beginners if so i will be glad to hear your comments about it. Stay closed the next article will be about how to create a yahoo messenger client written in php and implemented on the last version of YMSG protocol.

Albulescu Cosmin