PHP code example of janderson / json-rpc

1. Go to this page and download the library: Download janderson/json-rpc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

janderson / json-rpc example snippets


use Janderson\JsonRpc;

$json = '{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}';
$request = JsonRpc\Request::parse($json); // or ::read($object) with a parsed object or array

$response = is_array($request)
    ? array_filter(array_map(dispatch(...), $request))
    : dispatch($request);
    
echo json_encode($response);

function dispatch(JsonRpc\Request|JsonRpc\Response $request): JsonRpc\Response|null
{
    // Request error directly produces an error response
    if ($request->isError()) {
        return $request;
    }
    
    try {
        $result = call_your_function_of_choice($request->method, ...$request->params);
        return JsonRpc\Response::fromResult($result, $request); // Response (result) subtype
    } catch (\Exception $e) {
        return JsonRpc\Response::fromThrowable($e, $request); // Error subtype
    }
}

use Janderson\JsonRpc;

$request = JsonRpc\Request::request('subtract', [2, 1]);
$response = JsonRpc\Response::parse($client->send($request)); // HTTP client, or some other transport
if ($response->isError()) {
    throw new Exception($response->error->message, $response->error->code);
}
echo "Result is {$response->result}\n";