PHP code example of aicrion / json-rpc

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

    

aicrion / json-rpc example snippets


use Aicrion\JsonRpc\Attribute\RpcHandler;
use Aicrion\JsonRpc\Attribute\RpcMethod;
use Aicrion\JsonRpc\Kernel\RpcKernelBuilder;

#[RpcHandler('math')]
final class MathHandler
{
    #[RpcMethod]
    public function add(int $a, int $b): int
    {
        return $a + $b;
    }
}

$kernel = (new RpcKernelBuilder())
    ->withHandler(new MathHandler())
    ->build();

echo $kernel->dispatchJson(json_encode([
    'jsonrpc' => '2.0',
    'method' => 'math.add',
    'params' => ['a' => 2, 'b' => 3],
    'id' => 1,
]));
// {"jsonrpc":"2.0","id":1,"result":5}

#[RpcHandler('account')]
#[Protected_]
final class AccountHandler
{
    #[RpcMethod]
    public function balance(string $accountId): array { /* protected automatically */ }

    #[RpcMethod]
    #[Unprotected]
    public function ping(): string { /* explicitly opts out */ }
}

$kernel = (new RpcKernelBuilder())
    ->withHandler(new MathHandler())                                       // eager instance
    ->withHandlerClass(AccountHandler::class)                               // lazy, single class
    ->withDiscoveredHandlers(__DIR__ . '/src/Handler', 'App\\Handler')    // lazy, whole directory
    ->build();

$responses = $kernel->dispatchBatch([
    ['jsonrpc' => '2.0', 'method' => 'math.add', 'params' => [1, 2], 'id' => 1],
    ['jsonrpc' => '2.0', 'method' => 'math.add', 'params' => [5, 5]], // notification, no response
]);
// $responses contains only the answer to id=1

use Aicrion\JsonRpc\Pipeline\RateLimitStage;
use Aicrion\JsonRpc\Pipeline\LocalRateLimitStore;

$kernel = (new RpcKernelBuilder())
    ->withHandler(new MathHandler())
    ->withMiddleware(new RateLimitStage(new LocalRateLimitStore(), maxCallsPerMethod: 100, windowSeconds: 60))
    ->build();

final class LoggingListener implements RpcListener
{
    public function beforeInvoke(MethodDescriptor $d, array $args): void { /* ... */ }
    public function afterInvoke(MethodDescriptor $d, mixed $result): void { /* ... */ }
    public function onFailure(MethodDescriptor $d, Throwable $e): void { /* ... */ }
}

$kernel = (new RpcKernelBuilder())
    ->withHandler(new MathHandler())
    ->withListener(new LoggingListener())
    ->build();

use Aicrion\JsonRpc\Attribute\Cacheable;

#[RpcHandler('weather')]
final class WeatherHandler
{
    #[RpcMethod]
    #[Cacheable(ttlSeconds: 300)]
    public function forecast(string $city): array { /* ... */ }
}

$kernel = (new RpcKernelBuilder())
    ->withHandler(new WeatherHandler())
    ->withCacheStore(new InMemoryCacheStore())   // or FileCacheStore, ApcuCacheStore, RedisCacheStore
    ->build();

use Aicrion\JsonRpc\Pipeline\RateLimitStage;
use Aicrion\JsonRpc\Pipeline\LocalRateLimitStore;   // single server
use Aicrion\JsonRpc\Pipeline\RedisRateLimitStore;   // distributed

$kernel = (new RpcKernelBuilder())
    ->withHandler(new MathHandler())
    ->withMiddleware(new RateLimitStage(new RedisRateLimitStore($redisClient), maxCallsPerMethod: 100, windowSeconds: 60))
    ->build();

use Aicrion\JsonRpc\Exception\RpcErrorException;

#[RpcMethod]
public function withdraw(float $amount): array
{
    if ($amount > 100) {
        throw new RpcErrorException('Insufficient funds', -32020, ['available' => 100]);
    }

    return ['withdrawn' => $amount];
}