igaponov / jsonrpc

JsonRpc 2.0 PHP 规范

v1.0 2015-04-29 06:53 UTC

This package is not auto-updated.

Last update: 2024-09-14 16:24:11 UTC


README

JSON-RPC 是一种无状态的、轻量级的远程过程调用(RPC)协议。

Build Status Scrutinizer Code Quality Code Coverage

请求对象

通过向服务器发送一个请求对象来表示一个 RPC 调用。

// client
$request = new \JsonRpc\Spec\Request('subtract', [42, 23], 1);

// server
$result = call_user_func_array($request->getMethod(), $request->getParams());

通知

一个通知是一个没有 "id" 成员的请求对象。

$request1 = new \JsonRpc\Spec\Request('update', [1,2,3,4,5]);
$request2 = new \JsonRpc\Spec\Request('foobar');

响应对象

当发起一个 RPC 调用时,服务器必须回复一个响应,除非是通知。

$response = new \JsonRpc\Spec\Response($result, null, $request->getId());

错误对象

当 RPC 调用遇到错误时,响应对象必须包含一个错误成员,其值是一个 \JsonRpc\Spec\Error

$error = new \JsonRpc\Spec\Error(500, 'Internal error', $exception->getTraceAsString());
$response = new \JsonRpc\Spec\Response(null, $error, $request->getId());

从 -32768 到 -32000 的错误代码被保留用于预定义的错误。

use \JsonRpc\Spec\Exception\ParseErrorException;

try {
    // parse request
    throw new ParseErrorException();
} catch(ParseErrorException $e) {
    $error = new \JsonRpc\Spec\Error($e->getCode(), $e->getMessage(), $e->getTraceAsString());
    $response = new \JsonRpc\Spec\Response(null, $error, $request->getId());    
}

批处理

要同时发送多个请求对象,客户端可以发送一个填充了请求对象的数组

foreach($batch as $response) {
    $result = $response->getResult();
}

BatchRequest

$requests = [
    new \JsonRpc\Spec\Request('update', [1,2,3,4,5]),
    new \JsonRpc\Spec\Request('foobar'),
    // ...
];
$batch = new \JsonRpc\Spec\BatchRequest($requests);

BatchResponse

$responses = [
    new \JsonRpc\Spec\Response(7, 1),
    new \JsonRpc\Spec\Response(null, $error, 2),
    // ...
];
$batch = new \JsonRpc\Spec\BatchResponse($responses);

ObjectManager

对象管理器是处理请求/响应的包装器

$manager = new \JsonRpc\ObjectManager($transport);
$id = $manager->addRequest('subtract', [42, 23]);
$manager->addNotification('foobar');
$manager->commit();
if (!$manager->hasError($id)) {
    $result = $manager->getResult($id); // 19
} else {
    throw new Exception($manager->getError($id), $manager->getErrorCode($id));
}

传输

对象管理器使用一个传输对象与传输层(http、rabbitmq 等)通信。传输对象必须实现 \JsonRpc\TransportInterface

class CurlTransport implements \JsonRpc\TransportInterface 
{
    public function send(UnitInterface $data) 
    {
        $ch = curl_init();        
        
        $data = json_encode($data);        
        
        curl_setopt($ch, CURLOPT_URL, 'https:///rpc.php');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        
        curl_exec($ch);  
    }
}

测试

$ phpunit

许可

MIT 许可证(MIT)。请参阅许可文件获取更多信息。