PHP code example of tourze / json-rpc-core

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

    

tourze / json-rpc-core example snippets


use Tourze\JsonRPC\Core\Domain\JsonRpcMethodInterface;
use Tourze\JsonRPC\Core\Model\JsonRpcRequest;

class EchoMethod implements JsonRpcMethodInterface
{
    public function __invoke(JsonRpcRequest $request): mixed
    {
        return $request->getParams()->all();
    }

    public function execute(): array
    {
        return [];
    }
}

use Tourze\JsonRPC\Core\Exception\JsonRpcException;
use Tourze\JsonRPC\Core\Model\JsonRpcParams;
use Tourze\JsonRPC\Core\Model\JsonRpcRequest;
use Tourze\JsonRPC\Core\Model\JsonRpcResponse;

// 创建请求
$request = new JsonRpcRequest();
$request->setJsonrpc('2.0');
$request->setMethod('echo');
$request->setId('1');
$request->setParams(new JsonRpcParams(['message' => 'Hello, World!']));

// 创建方法实例
$method = new EchoMethod();

// 执行方法并获取响应
$response = new JsonRpcResponse();
$response->setJsonrpc('2.0');
$response->setId($request->getId());

try {
    $result = $method($request);
    $response->setResult($result);
} catch (JsonRpcException $e) {
    $response->setError($e);
} catch (\Throwable $e) {
    // 将普通异常包装为 JSON-RPC 异常
    $jsonRpcException = new JsonRpcException(-32000, $e->getMessage());
    $response->setError($jsonRpcException);
}