AMFPHP – transparent AMF and JSON serialisation
29 Dec 2010Getting Javascript to Talk to AMFPHP.
It’s a great advantage to have web applications degrade from HTML5 to Flash. Why? Because it allows a greater cross-compatability between browsers.
Transparent JSON in AMFPHP isn’t as easy as submitting POST data to json . php . You’ll quickly notice raising errors results in: Fatal error: Class ‘ErrorMessage’ not found in /amfphp 1.9/core/shared/exception/MessageException.php on line 63
To resolve this, put this in your service PHP file (in my case, MyService.php):
// JSON does not have Error Message
if (!class_exists('ErrorMessage')) { class ErrorMessage{};}
Another transparent issue is the lack of class serialisation. Simply set the _explicitType string in the Javascript class to the local VO object, and it will change them for you:
/**
* loops through JSON array, replaces Arrays with serialized classes
* @see mapClass($typeIdentifier) AMFBaseDeserializer.php
* @param <type> $arr
*/
public function mapJSONClasses (& $arr) {
if(is_array($arr)) {
foreach ($arr as $key => $value) {
$this->mapJSONClasses($arr[$key]);
}
if(isset($arr['_explicitType'])) {
$mappedClass = str_replace('.', '/', $arr['_explicitType']);
$lastPlace = strrpos('/' . $mappedClass, '/');
$classname = substr($mappedClass, $lastPlace);
if(class_exists($classname)) {
$clazz = new $classname;
foreach ($arr as $key => $value) {
if ($key == '_explicitType') continue;
$clazz->$key = $value;
}
$arr = $clazz;
}
}
}
}