bednic/json-rpc

JSON RPC 2.0 implementation


Keywords
rpc, php, json
License
MIT

Documentation

JSON RPC 2.0 Implementation

JSON RPC Docs

JSON-RPC

Usage

  1. Create command
  2. Add command to dispatcher
  3. Add dispatcher to your controller and pass the request

Optionally you can use JSONRPCMiddleware to check right media type

Example

<?php
class ImportData implements \JSONRPC\Procedure
{

    public function getMethodName(): string
    {
        return 'import_data';
    }
    /**
     * @param array $params
     *
     * @return mixed
     * @throws \JSONRPC\Exception\InternalError
     */
    public function execute(array $params)
    {
        try {
            // do your stuff
            return "ok";
        } catch (\Throwable $exception) {
            throw new \JSONRPC\Exception\InternalError($exception->getMessage(), -32603, $exception);
        }
    }

    /**
     * @return \JSONRPC\Description
     */
    public function getDescription(): \JSONRPC\Description
    {
        $desc = new \JSONRPC\Description();
        $desc->addParameter('path', 'Path where data are stored', false);
        $desc->setDescription("Import data from path to database");
        return $desc;
    }

}

$dispatcher = new JSONRPC\Dispatcher();
$command = new ImportData();
$dispatcher->addCommand($command);
/** @var \Psr\Http\Message\ServerRequestInterface $serverRequest */
$result = $dispatcher->dispatch($serverRequest);
/** @var \Psr\Http\Message\ResponseInterface $response */
$response->write(json_encode($result));

That's it!