PHP code example of igaponov / jsonrpc

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

    

igaponov / jsonrpc example snippets


// client
$request = new \JsonRpc\Spec\Request('subtract', [42, 23], 1);

// server
$result = call_user_func_array($request->getMethod(), $request->getParams());

$request1 = new \JsonRpc\Spec\Request('update', [1,2,3,4,5]);
$request2 = new \JsonRpc\Spec\Request('foobar');

$response = new \JsonRpc\Spec\Response($result, null, $request->getId());

$error = new \JsonRpc\Spec\Error(500, 'Internal error', $exception->getTraceAsString());
$response = new \JsonRpc\Spec\Response(null, $error, $request->getId());

use \JsonRpc\Spec\Exception\ParseErrorException;

try {
    // parse request
    throw new ParseErrorException();
} catch(ParseErrorException $e) {
    $error = new \JsonRpc\Spec\Error($e->getCode(), $e->getMessage(), $e->getTraceAsString());
    $response = new \JsonRpc\Spec\Response(null, $error, $request->getId());    
}

foreach($batch as $response) {
    $result = $response->getResult();
}

$requests = [
    new \JsonRpc\Spec\Request('update', [1,2,3,4,5]),
    new \JsonRpc\Spec\Request('foobar'),
    // ...
];
$batch = new \JsonRpc\Spec\BatchRequest($requests);

$responses = [
    new \JsonRpc\Spec\Response(7, 1),
    new \JsonRpc\Spec\Response(null, $error, 2),
    // ...
];
$batch = new \JsonRpc\Spec\BatchResponse($responses);

$manager = new \JsonRpc\ObjectManager($transport);
$id = $manager->addRequest('subtract', [42, 23]);
$manager->addNotification('foobar');
$manager->commit();
if (!$manager->hasError($id)) {
    $result = $manager->getResult($id); // 19
} else {
    throw new Exception($manager->getError($id), $manager->getErrorCode($id));
}

class CurlTransport implements \JsonRpc\TransportInterface 
{
    public function send(UnitInterface $data) 
    {
        $ch = curl_init();        
        
        $data = json_encode($data);        
        
        curl_setopt($ch, CURLOPT_URL, 'http://localhost/rpc.php');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        
        curl_exec($ch);  
    }
}