PHP code example of nathan-muir / json-rpc-2

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

    

nathan-muir / json-rpc-2 example snippets



namespace MyCompany\Package;

use \Ndm\JsonRpc2\Client\HttpClient;
// use vendor autoload from composer
// call a method, using named parameters
$client->call('somemethod', array('abc'=>123));

// alternatively, use the "native" interface
$nativeClient = $client->getNativeClient();
// however calls must use positional parameters
$nativeClient->somemethod(123);






namespace MyCompany\Package;

use Ndm\JsonRpc2\HttpServer;
use \Ndm\JsonRpc2\Server\Exception\TransportReceiveException;
use \Ndm\JsonRpc2\Server\Exception\TransportReplyException;

server with a set of methods, either from an instance, a class with static methods, or as a map of 'callables'
$server = HttpServer::register( $api, 'StaticClass',$methods);

// process the request!
try {
    $server->process();
} catch (TransportReceiveException $treceive){
    // exceptions on this layer - like not using HTTP-POST
    header('HTTP/1.0 400 Bad Request');
    exit;
} catch (TransportReplyException $treply){
    header('HTTP/1.0 500 Internal Server Error');
    exit;
}





namespace MyCompany\Package;

use \Ndm\JsonRpc2\Server\Server;
use \Ndm\JsonRpc2\Server\Exception\TransportReceiveException;
use \Ndm\JsonRpc2\Server\Exception\TransportReplyException;
use \Ndm\JsonRpc2\Server\Transport\HttpTransport;
use \Ndm\JsonRpc2\Server\Dispatch as Dispatch;

create a server with the aforementioned dispatch & transport systems

// the transport - a simple http wrapper
$transport = new HttpTransport(HttpTransport::OPT_REQUIRE_HTTPS | HttpTransport::OPT_SEND_OUTPUT_HEADERS);


$api = new SomeClass();

//create a set of methods from the instance of SomeClass
$methods = Dispatch\ReflectionMethod::createFrom($api);
// dispatch system is responsible for invoking methods called by clients
$dispatch = new Dispatch\MapDispatch();
// register all the methods with the dispatch system
$dispatch->registerAll($methods);

// start the server
$server = new Server($transport, $dispatch);
// process the request!
try {
    $server->process();
} catch (TransportReceiveException $treceive){
    header('HTTP/1.0 400 Bad Request');
    exit;
} catch (TransportReplyException $treply){
     header('HTTP/1.0 500 Internal Server Error');
     exit;
}