So I started playing with Zend_Json_Server and was having a hard time trying to figure out how to call the server from a client. Finally I checked the JSON-RPC 2.0 spec and read a very important detail that I had not realized:
The Request is expressed as a single JSON Object
This was the key to my problem. There are 4 parameters that can be sent with each JSON-RPC 2.0 request but I was sending each as a post var which is not what Zend_Json_Server expects. It simply wants one json encoded object with all the parameters inside. The 4 available parameters are:
- jsonrpc – the version you are using; I’m using 2.0.
- method – the name of the method you want to call in the server.
- params – object of parameters your method needs. If you don’t need any, don’t send this param.
- id – an identifier (anything you want) that will be sent to and from the server for this request.
I’m using Zend_Http_Client() to make the request and here is an example:
‘jsonrpc’ => ’2.0′,
‘method’ => ‘find’,
‘params’ => array(’326691′),
‘id’ => ‘test’
$http = new Zend_Http_Client();
And here is what I see in my browser when I make the call:
address: "some place"
Basically, all I had to do was
- create an array of all the parameters I want to send on my request object. I’m calling the find method and passing an id
- create a new client object
- set the url to where your setting up your Zend_Json_Server
- set the client to post (Zend_Json_Server only seems to handle post at this time)
- json_encode your parameters array
- pass the json_encoded object to the setRawData so it passes exactly what we want which is one json object to the server
- call request to send the request and finally get body to show the response.
Here is my code for the server.php file so you can see how I’m setting up the server:
$response = $server->handle();
I setup the server instance, add a class to handle the requests, call handle and echo the response. Student will look for the Student.php class so make sure it’s available in your include paths. That’s it, hope you found this helpful. As a side note, I noticed Zend_Amf_Server has a method to addDirectory instead of adding each class separately. Hopefully this gets added to Zend_Json_Server at some point.