As promised in my introductory post, I shall demonstrate how to use AMFPHP in Flex3 in order to perform CRUD (create, retrieve/read, update, delete) operations on the tuples of a table. We will make use of AMFPHP Remoting to invoke RPCs that will perform CRUD operations on a mysql database.
Before we are set to go, let me give you a brief insight into AMF. AMF is the Action Messaging Format and is used for serializing messages between the webserver and Flex. It is about 10 times faster than using the HTTPService Objects as it uses a binary format to serialize the messages and allows mirroring of server side classes on the Flex client (how this can be done will be covered in a different post). AMFPHP is a PHP Open Source library which allows PHP Classes to talk to Flex .
1. Setting it up
AMFPHP can be downloaded from here
Once you have extracted the archive, paste into your web root or any folder your webserver can access. A clean install can be verified by checking the url http://<path_your_pasted_dir>/gateway.php
2. Writing a Service
Since this post has been talking a lot about classes, you might have figured by now that we will be using OO PHP for writing the service. As mentioned earlier, I shall not talk about the mapping of VOs in this blog post.
I shall call my service as TestService.php, and I have four methods-
feedData- to insert records
getData- to retrieve records
updateData- to update records
deleteData- to remove records
This is the table that I will be working with-
CREATE TABLE `users` (
`id` int(3) NOT NULL auto_increment,
`name` varchar(20) NOT NULL,
`city` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `city`) VALUES
(1, 'Tom', 'London'),
(3, 'Harry', 'dfgfg'),
(4, 'foo', 'bar'),
(5, 'abc', 'xyz'),
(6, 'sdlj', 'dfdf;');
It is a sample users table with each tuple of the form (id,name,city)
TestService.php
<?php
include('db.php') //define all DB connection settings here;
/**
* TestService to demonstrate CRUD
* Author: tusay
* The PHP Codes here are pragmatic in nature, importance to be given to usage of function parameters and return types
*/
class TestService {
/**
* Inserts a record
* @returns Flag to indicate success or failure
*/
public function feedData($name,$city) {
//Connect to the DB
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$query="insert into users(name,city) values('$name','$city')";
if(mysqli_query($dbc,$query))
return "true";
else return "false";
mysqli_close($dbc);
}
/**
* Gets all the records as an array
*
*/
public function getData() {
//Connect to the DB
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$returnValue=array();
$query="select * from users";
$result=mysqli_query($dbc,$query) or die("Error in SQL Query, please check the SQL");
while($row=mysqli_fetch_array($result,MYSQL_ASSOC))
{
$returnValue[]=$row;
}
mysqli_close($dbc);
return $returnValue;
}
/**
* Deletes a record
* @returns Flag to indicate success or failure
*/
public function deleteData($name) {
//Connect to the DB
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$query="DELETE FROM users WHERE name='$name' LIMIT 1";
if(mysqli_query($dbc,$query))
return "true";
else return "false";
mysqli_close($dbc);
}
public function updateData($name,$new_city) {
//Connect to the DB
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$returnValue=array();
$query="update users set city='$new_city' where name='$name'";
$result=mysqli_query($dbc,$query) or die("Error in SQL Query, please check the SQL");
if($result)
{
$returnValue['flag']="true";
}
else
$returnValue['flag']="false";
mysqli_close($dbc);
return $returnValue;
}
}
?>
Notice that in all cases other that than feedData, the return value is flag denoting the status of the operation. A function may return a single value, an array of key-value pairs or an array of objects too. The service must go to the services folder inside your amfphp directory.
3. Testing the Service
Once you have the service ready, its better to test it before using it in your Flex Project. For this purpose, AMFPHP provides an excellent Service Browser (which itself is a Flex application). You will find the Service Browser in the browser directory inside your amfphp installation. Here you can make method invocations and it will show you the results of the operations. It also provides other statistical information of interest such as the total time reuired for the invocation, encode time, send/receive time, decode time, network time etc.
4. Using the Service In Flex
In order to use the written service, we will use the Remote Object-
<mx:RemoteObject id=“yourRemoteObject" source="yourAMFPHPFolderName.ThePHPFile" destination="amfphp" showBusyCursor="true">
<mx:method name="theFunctionYouWantToCall" result="myFunctionResultHandler(event)" fault="myFunctionFaultHandler(event)"/>
</mx:RemoteObject>
Notice that the source attribute takes the value- yourAMFPHPFolderName.ThePHPFile where AMFPHPFolderName is the name of the folder inside the aforementioned services folder and ThePHPFile (without the .php extension) is the name of the service (and also the PHP class).
You then write out the methods associated with the particular service, taking care that theFunctionYouWantToCall shares the same name as that in the service you have just written out in PHP. On a successful invocation of the method, the Action Script result handler (myFunctionResultHandler, in this case) will be invoked, in case of an error the Action Script error handler (myFunctionFaultHandler, in this case) will be invoked. All this happens asynchronously.
5. Coding the Action Script Handlers
private function myFunctionResultHandler(event:ResultEvent):void
{
var PHPResult:String=String(event.result);
Alert.show(PHPResult); //will show what the PHP class returned
}
This means the PHP function has a return statement like this:
return $value
OR
return "Test";
private function myFunctionResultHandler(event:ResultEvent):void
{
Alert.show("Name: "+event.result.name);
Alert.show("Age: "+event.result.age);
}
This means the PHP returns key-value pairs like this:
$returnValue=array();
$returnValue['name']=“tusay”;
$age=21;
$returnValue['age']=$age;
return $returnValue;
You may code the result handlers so as to use the retrieved tuples as data providers to controls.
The error handler may be coded as follows-
private function myFunctionFaultHandler(event:FaultEvent):void
{
Alert.show(event.message.toString());
}
If you want to see a working sample of the project, please refer to my first post to get the Flex Project and the other assets.
AMFPHP is a PHP open source library