PHP code example of json-rpc / server

1. Go to this page and download the library: Download json-rpc/server 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/ */

    

json-rpc / server example snippets




/**
 * Handler resolver
 */
final class CustomHandlerResponse implements \JsonRpc\HandlerResolver
{
    /**
    * @param array<string,\JsonRpc\RequestHandler|\JsonRpc\NotificationHandler> $handlers
     */
    public function __construct(private array $handlers = [])
    {}

    public function resolve(string $method) : \JsonRpc\RequestHandler|\JsonRpc\NotificationHandler{
        if (!array_key_exists($method, $this->handlers)) {
            throw new \JsonRpc\MethodHandlerNotFound($method);
        }

        return $this->handlers[$method];
    }
}

/**
* "sum" method handler
 */
final class SumMethodHandler implements \JsonRpc\RequestHandler {
    public function handle(\JsonRpc\Request\Request $request): int
    {
        return $request->params[0] + $request->params[1];
    }
}

$request = <<<JSON
    {
        "jsonrpc": "2.0",
        "method": "sum",
        "params": [1,2],
        "id": 1
    }
JSON;

$resolver = CustomHandlerResolver([
    'sum' => new SumMethodHandler(),
]);
$server = new Server($resolver);
$response = $server->respond($request);

/**
 * {
 *  "jsonrpc": "2.0",
 *  "result": 3,
 *  "id": 1
 * }
 */