Zend\Json\Server is a JSON-RPC server implementation. It supports both the JSON-RPC version 1 specification as well as the version 2 specification; additionally, it provides a PHP implementation of the Service Mapping Description (SMD) specification for providing service metadata to service consumers.
JSON-RPC is a lightweight Remote Procedure Call protocol that utilizes JSON for its messaging envelopes. This JSON-RPC implementation follows PHP‘s SoapServer API. This means, in a typical situation, you will simply:
Zend\Json\Server utilizes Zend\Server\Reflection to perform reflection on any attached classes or functions, and uses that information to build both the SMD and enforce method call signatures. As such, it is imperative that any attached functions and/or class methods have full PHP docblocks documenting, minimally:
Zend\Json\Server listens for POST requests only at this time; fortunately, most JSON-RPC client implementations in the wild at the time of this writing will only POST requests as it is. This makes it simple to utilize the same server end point to both handle requests as well as to deliver the service SMD, as is shown in the next example.
Zend\Json\Server Usage
First, let’s define a class we wish to expose via the JSON-RPC server. We’ll call the class ‘Calculator’, and define methods for ‘add’, ‘subtract’, ‘multiply’, and ‘divide’:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /**
* Calculator - sample class to expose via JSON-RPC
*/
class Calculator
{
/**
* Return sum of two variables
*
* @param int $x
* @param int $y
* @return int
*/
public function add($x, $y)
{
return $x + $y;
}
/**
* Return difference of two variables
*
* @param int $x
* @param int $y
* @return int
*/
public function subtract($x, $y)
{
return $x - $y;
}
/**
* Return product of two variables
*
* @param int $x
* @param int $y
* @return int
*/
public function multiply($x, $y)
{
return $x * $y;
}
/**
* Return the division of two variables
*
* @param int $x
* @param int $y
* @return float
*/
public function divide($x, $y)
{
return $x / $y;
}
}
|
Note that each method has a docblock with entries indicating each parameter and its type, as well as an entry for the return value. This is absolutely critical when utilizing Zend\Json\Server or any other server component in Zend Framework, for that matter.
Now we’ll create a script to handle the requests:
1 2 3 4 5 6 7 | $server = new Zend\Json\Server\Server();
// Indicate what functionality is available:
$server->setClass('Calculator');
// Handle the request:
$server->handle();
|
However, this will not address the issue of returning an SMD so that the JSON-RPC client can autodiscover methods. That can be accomplished by determining the HTTP request method, and then specifying some server metadata:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $server = new Zend\Json\Server\Server();
$server->setClass('Calculator');
if ('GET' == $_SERVER['REQUEST_METHOD']) {
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget('/json-rpc.php')
->setEnvelope(Zend\Json\Server\Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return;
}
$server->handle();
|
If utilizing the JSON-RPC server with Dojo toolkit, you will also need to set a special compatibility flag to ensure that the two interoperate properly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $server = new Zend\Json\Server\Server();
$server->setClass('Calculator');
if ('GET' == $_SERVER['REQUEST_METHOD']) {
$server->setTarget('/json-rpc.php')
->setEnvelope(Zend\Json\Server\Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();
// Set Dojo compatibility:
$smd->setDojoCompatible(true);
header('Content-Type: application/json');
echo $smd;
return;
}
$server->handle();
|
While most functionality for Zend\Json\Server is spelled out in this section, more advanced functionality is available.
Zend\Json\Server\Server is the core class in the JSON-RPC offering; it handles all requests and returns the response payload. It has the following methods:
The JSON-RPC request environment is encapsulated in the Zend\Json\Server\Request object. This object allows you to set necessary portions of the JSON-RPC request, including the request ID, parameters, and JSON-RPC specification version. It has the ability to load itself via JSON or a set of options, and can render itself as JSON via the toJson() method.
The request object has the following methods available:
An HTTP specific version is available via Zend\Json\Server\Request\Http. This class will retrieve the request via php://input, and allows access to the raw JSON via the getRawJson() method.
The JSON-RPC response payload is encapsulated in the Zend\Json\Server\Response object. This object allows you to set the return value of the request, whether or not the response is an error, the request identifier, the JSON-RPC specification version the response conforms to, and optionally the service map.
The response object has the following methods available:
An HTTP specific version is available via Zend\Json\Server\Response\Http. This class will send the appropriate HTTP headers as well as serialize the response as JSON.
JSON-RPC has a special format for reporting error conditions. All errors need to provide, minimally, an error message and error code; optionally, they can provide additional data, such as a backtrace.
Error codes are derived from those recommended by the XML-RPC EPI project. Zend\Json\Server appropriately assigns the code based on the error condition. For application exceptions, the code ‘-32000’ is used.
Zend\Json\Server\Error exposes the following methods:
SMD stands for Service Mapping Description, a JSON schema that defines how a client can interact with a particular web service. At the time of this writing, the specification has not yet been formally ratified, but it is in use already within Dojo toolkit as well as other JSON-RPC consumer clients.
At its most basic, a Service Mapping Description indicates the method of transport (POST, GET, TCP/IP, etc), the request envelope type (usually based on the protocol of the server), the target URL of the service provider, and a map of services available. In the case of JSON-RPC, the service map is a list of available methods, which each method documenting the available parameters and their types, as well as the expected return value type.
Zend\Json\Server\Smd provides an object-oriented way to build service maps. At its most basic, you pass it metadata describing the service using mutators, and specify services (methods and functions).
The service descriptions themselves are typically instances of Zend\Json\Server\Smd\Service; you can also pass all information as an array to the various service mutators in Zend\Json\Server\Smd, and it will instantiate a service for you. The service objects contain information such as the name of the service (typically the function or method name), the parameters (names, types, and position), and the return value type. Optionally, each service can have its own target and envelope, though this functionality is rarely used.
Zend\Json\Server\Server actually does all of this behind the scenes for you, by using reflection on the attached classes and functions; you should create your own service maps only if you need to provide custom functionality that class and function introspection cannot offer.
Methods available in Zend\Json\Server\Smd include:
Zend\Json\Server\Smd\Service has the following methods:
The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.