PHP code example of mihasicehcek / php_json_rpc_2_server
1. Go to this page and download the library: Download mihasicehcek/php_json_rpc_2_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/ */
mihasicehcek / php_json_rpc_2_server example snippets
//simulating a request
$json = json_encode([
"jsonrpc" => "2.0",
"method" => "Calculator.sum",
"params" => [ "a" => 10, "b" => 15],
"id" => 1
]);
//Creating instance of \PhpJsonRpc2\JsonRpcServer
$jsonRpcServer = new \PhpJsonRpc2\JsonRpcServer();
//Passing json string
$jsonRpcServer->setRequestAsJson($json);
//geting Response
$response = $jsonRpcServer->getResponse();
echo json_encode($response); //{ jsonrpc : "2.0", result : 2, id : 1}
$json = json_encode([
"jsonrpc" => "2.0",
"method" => "Calculator.sum",
"params" => [10, 15],
"id" => 1
]);
//Create request from json
$request = Request::requestFactory($json);
$jsonRpcServer = new \PhpJsonRpc2\JsonRpcServer();
//pass json into setRequest method
$jsonRpcServer->setRequest($request);
$response = $jsonRpcServer->getResponse();
echo json_encode($response); //{ jsonrpc : "2.0", result : 2, id : 1}
//Create our implementation if \PhpJsonRpc2\ICallStrategy interface(For simplicity, we imagine that we pass only the positional parameters)
class SimpleMethodCallStrategy implements ICallStrategy
{
/**
*@param $method string method name(define in "method" parameter of json object)
*@param $params array It can be as indexing and associative array
*/
public function call($method, $params)
{
$function = new \ReflectionFunction($method);
return $function->invokeArgs($params);
}
}
$request = [
"jsonrpc" => "2.0",
"method" => "sum",
"params" => [10, 15],
"id" => 1
];
$json = json_encode($request);
$jsonRpcServer = new \PhpJsonRpc2\JsonRpcServer();
//configure instance of JsonRpcServer by insatnce of SimpleMethodCallStrategy
$jsonRpcServer->setCallStrategy(new SimpleMethodCallStrategy());
$jsonRpcServer->setRequestAsJson($json);
$response = $jsonRpcServer->getResponse();
echo json_encode($response); //{ jsonrpc : "2.0", result : 2, id : 1}