Mapping Data Types from PHP to Flex with Zend AMF and Flash Builder 4

I assume this has to be out there somewhere but I couldn’t find it so hopefully this helps someone who Google’s things the same way I do. And Wade has a great tutorial for doing this when you’re just dealing with the Zend AMF code but I was looking for something that worked with Flash Buidler 4’s wizards.

While using the Flash Builder 4 data-centric design wizards to generate the service calls for a PHP class I was having trouble figuring out how to make sure that the data types I had set up in my MySQL database were being carried all the way through to my Flex application. When I retrieved data from the database in PHP and then had Flash Builder 4 inspect my class, the properties of my returned class were all strings.

If you use the data-centric design wizards to create a class based on a database, the class properties are typed correctly. If you use a class you’ve already written, all of the properties come back as strings. Luckily I chatted with our Flex/PHP guru, Mihai Corlan, and he pointed me in the direction of type casting.

Essentially you just need to add a bit of extra data when the properties are returned in the class so that Zend AMF knows what type of data to expect. So for my getAllItems() method, I iterate through the records of my database and create a PHP object for each one.

As you can see in the code below, to return as an int, just add a 0, to set it as a number, add 0.0, to set it as a date, just create a new DateTime object with the data from MySQL. As you can see from the Mapping Table you’ve got coverage for pretty much every data type.

public function getAllForests()
{
$this->connect();
$rs = mysql_query("select * from national_forests")
or die ("Unable to complete query.");
 
$national_forests = array();
 
while( $row = mysql_fetch_assoc($rs) )
{
$forest = new NationalForest();
$forest->id = $row['id']+0;
$forest->state = $row['state'];
$forest->area = $row['area']+0.0;
$forest->established = new DateTime($row['established']);
$forest->closest_city = $row['closest_city'];
$forest->name = $row['name'];
 
array_push($national_forests,$forest);
}
 
return $national_forests;
}

If there’s a better way to do this, I’d love to have it.

Show Comments

Hide Comments

Comments are closed.