PHP code example of vaderangry / php-json-rpc

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

    

vaderangry / php-json-rpc example snippets




use PhpJsonRpc\Server;

// Class for which provide JSON-RPC2 API:
class Math
{
    public function pow(float $base, int $exp): float
    {
        return pow($base, $exp);
    }
}

$server = new Server();

$response = $server
    ->addHandler(new Math())
    ->execute();

echo $response;



use PhpJsonRpc\Server;
use PhpJsonRpc\Server\MapperInterface;

// Define custom mapper
class Mapper implements MapperInterface
{
    public function getClassAndMethod(string $requestedMethod): array
    {
        // Keys of array presents requested method
        $map = [
            'pow' => [Math::class, 'pow'],
        ];

        if (array_key_exists($requestedMethod, $map)) {
            return $map[$requestedMethod];
        }

        return ['', ''];
    }
}

$server = new Server();

// Register new mapper
$server->setMapper(new Mapper());

// Register handler and run server
$response = $server->addHandler(new Math())->execute();

echo $response;



use PhpJsonRpc\Client;

$client = new Client('http://localhost');
$result = $client->call('Math.pow', [2, 3]); // $result = 8
$result = $client->call('Math.methodNotFound', []); // $result = null



use PhpJsonRpc\Client;

$client = new Client('http://localhost', Client::ERRMODE_EXCEPTION);
$result = $client->call('Math.methodNotFound', []); // throw MethodNotFoundException



use PhpJsonRpc\Client;

$client = new Client('http://localhost');

$result = $client->batch()
    ->call('Util.Math.pow', [2, 1])
    ->call('Util.Math.pow', [2, 2])
    ->call('Util.Math.pow', [2, 3])
    ->call('Util.methodNotFound', [])
    ->batchExecute();
// $result = [2, 4, 8, null]



use PhpJsonRpc\Client;

$client = new Client('http://localhost', Client::ERRMODE_EXCEPTION);

$result = $client->batch()
    ->call('Util.Math.pow', [2, 1])
    ->call('Util.methodNotFound', [])
    ->batchExecute();
// $result = [2, MethodNotFoundException]



use PhpJsonRpc\Client;
use PhpJsonRpc\Common\Interceptor\Container;
use PhpJsonRpc\Common\Interceptor\Interceptor;

$client = new Client('http://localhost');

$client->getTransport()->onPreRequest()
   ->add(Interceptor::createWith(function (Container $container) {
        // Get transport from container
        $transport = $container->first();

        // Add