PHP code example of barell / json-rpc-server

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

    

barell / json-rpc-server example snippets


class ExampleService
{
    public function hello($name)
    {
        return 'Hello ' . $name . '!';
    }
}

use JsonRpcServer\Server;

// Create server instance with default options
$server = Server::createDefault();

// Add hello method from ExampleService class
$server->addMethod('hello', 'ExampleService');

// Alternatively add get method from UserService class but expose it as getUser
$server->addMethod('getUser', 'UserService', 'get');

// Finally handle and output the result
$server->handle()->output();

use JsonRpcServer\IHandler;

class MyHandler implements IHandler
{
    public function getData()
    {
        // Implement your own source of incoming data here...
    }
}

// Create server
$server = Server::createDefault();

// Tell server to use your handler
$server->setHandler(new MyHandler());

use JsonRpcServer\ICodec;

class MyCodec implements ICodec
{
    public function decode($data)
    {
        // decode json rpc object using your own implementation
    }
    
    public function encode($data)
    {
        // encode PHP array response into json string
    }
}

// Create server
$server = Server::createDefault();

// Tell server to use your handler
$server->setCodec(new MyCodec());

class ExampleService
{
    public function divide($a, $b)
    {
        if ($b == 0) {
            throw new JsonRpcUserException('Division by zero is not allowed', 1234);
        }
        
        return $a / $b;
    }
}