About JSON support

Posted on

Before people start crying about feature bloat, let me put things in perspective. There are two files in the json directory, totaling 5k. That’s it. Amfphp has had a JSON parser in it since amfphp 1.2 (the PEAR version, for the service browser), so it didn’t need a lot to get it to support JSON.

How it works: To make a request, call /json.php/com.mypackage.MyClass.myMethod/arg1/arg2 (and so on for other arguments). arg1 or arg2 can be strings with or without surrounding quotes, numbers, arrays or objects in JSON format. The myMethod method will be called in class MyClass in the services/com/mypackage folder, with arguments arg1 and arg2 (decoded). Then you can send back whatever you want and it will serialize automatically. If you use NetDebug::trace it will add that in a comment before the actual data. It will serialize recordsets like amfphp does by creating an object which has two keys: “columns” (an array) and “rows” (an array of arrays). You can then easily manipulate this data in JavaScript. If you want to use it with Spry, you can see my example jsondataset.js file which does all the job for you (if anybody at Adobe is listening, you can add it or something along the lines of it in the next version of Spry). If you add POST data to your request it will be deserialized as JSON and you will receive it as the last argument to your method.

Now, why would you use JSON in amfphp instead of, say, library X? Well:

  • You can use the same service in JavaScript AND Flash.
  • You can use the service browser to test your classes.
  • Most PHP Ajax libraries mix and match code and presentation in a fashion which makes me sick to the stomach. Amfphp provides a clean way to organize your code and dispatch calls.
  • It will use PHP’s json_* functions if it finds them (built-in in PHP 5.2, available as an extension in older versions), or will revert to PEAR JSON if it doesn’t, so you have an easy upgrade path if you need more speed.
  • It will serialize recordsets directly.
  • It doesn’t have any JavaScript dependencies, so you can use with whatever toolkit you like (prototype, MochiKit, Spry, you name it).

(I would also say personally that it’s entirely fuggawesome, but I think I’ve already made a pretty strong argument for that).

About XML-RPC support

XML-RPC is similar to SOAP except that it doesn’t rely on those godforsaken .wsdl files. It’s a lot more verbose that JSON-RPC or AMF-RPC but it’s readable, and if you enable gzip compression it’s not that bad as far as size goes. It could be useful if you want to share your awesome new service with XML-heads. It requires the xmlrpc extension to be installed. Just call xmlrpc.php through POST and it should work like you expect it to (that is, it uses the same kind of mapping as the “normal” amfphp does, it’ll serialize recordsets, etc.)