-
Notifications
You must be signed in to change notification settings - Fork 29
Server usage
Setting up your server is simple. All you need is a class containing the methods that you expose to the client, which you pass to the constructor of JsonRpc\Server
. For an instantiated class:
<?php
$methods = new MethodsClass();
$server = new JsonRpc\Server($methods);
For a static class:
<?php
$server = new JsonRpc\Server('\\\\Namespace\\\\MethodsStatic');
Then you call the $server->receive
method, which will do all the work for you:
<?php
$server->receive();
And that is it. The library will handle all Json-Rpc requests, including notification and batch requests, invoke your methods and return the response. It also handles any errors it may encounter. The requirements of the methods class are described below:
It must be a class, because the library uses Reflection
to check and order the method parameters. If you used an ordinary function
or closure
this would not be possible.
It should contain a public property error
which is used by your methods to signify an error and is returned by the server as an appropriate error response. Take a look at an example method class below.
<?php
class MyMethodsClass
{
public $error = null;
public function divide($dividend, $divisor, $int = false)
{
if (!$divisor)
{
$this->error = 'Cannot divide by zero';
}
else
{
$quotient = $dividend / $divisor;
return $int ? (int) $quotient : $quotient;
}
}
}
If the divide
method is passed 0
as its divisor, it sets its error property to a string message. The server checks for this and returns an appropriately formatted JSON-RPC response:
{"jsonrpc": "2.0", "error": {"code": -32000, "message": "Server error", "data": "Cannot divide by zero"}, "id": 1}
This format is explained in the official specification. However, it is worth noting that the error code used is reserved for "implementation-defined server-errors" and that the original error is passed as the data
member of the error structure. You can set your own error codes (in the range -32000 to -32099) and messages. For example the above error could be set as an array:
<?php
$this->error = array(
'code' => -32000,
'message' => 'Server error',
'data' => 'Cannot divide by zero'
);
It could also be set as an object. The library uses the following rules for interpreting the error
property of the method class:
- if it is an integer it is set as the code:
{"code": <error>, "message": "Server error"}
- if it is a scalar it is set as the data:
{"code": -32000, "message": "Server error","data":<error>}
- if an array or object it uses any values it finds, defaulting to:
{"code": -32000, "message": "Server error"}
* Note that an Exception
will be thrown if you set the error code outside of the accepted range.
- if the method call does not have the required number of parameters
- if an
Exception
occurs in your method
These are returned with the appropriate error response.