operation-hardcode / php-rpc-server
PHP 的 JSON RPC 服务器实现。
Requires (Dev)
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.15
This package is not auto-updated.
Last update: 2024-09-25 17:44:53 UTC
README
PHP 的 JSON RPC 服务器实现。
json-rpc 是一个非常简单的协议。您可以通过阅读 协议规范 来了解这一点。
这个库实现了 json-rpc 服务器规范。它易于使用且类型良好。
内容
安装
composer require operation-hardcode/php-rpc-server
用法
由于 json-rpc 服务器只有一个端点,您需要一个处理程序来根据方法名称确定要处理的请求的处理程序。如果您实现了 OperationHardcode\PhpRpcServer\RpcHandler
接口,可以自己编写它。或者使用库中提供的现成处理程序,即 OperationHardcode\PhpRpcServer\InvokableRpcHandler
。
要开始使用 rpc 服务器,实例化 RpcServer
use OperationHardcode\PhpRpcServer\RpcServer; use OperationHardcode\PhpRpcServer\RpcRequest; use OperationHardcode\PhpRpcServer\RpcResponse; use OperationHardcode\PhpRpcServer\Protocol\Validation\ValidateRequest; $server = RpcServer::new([ 'users.get' => function (RpcRequest $request, ?RpcResponse $response = null): ?RpcResponse { return $response?->addResult([10, 11]); } ]) $server->process('{"jsonrpc": "2.0", "method": "users.get", "id": 1}');
rpc-server 不会获取 json,它只是根据规范进行处理。这为您使用服务器提供了自由度,因为您可以通过您知道的方式传递获取的 json:通过 http、web sockets 或甚至通过 tcp。
如您所注意到的,处理程序可能没有 RpcResponse 对象。如果是这样,它是一个通知,而不是请求,因此不会向客户端发送响应。您可以简单地返回此对象(因为它为 null)或直接返回 null。
rpc-server 使用验证器来验证 json 是否符合规范。如果您想添加自己的验证器,必须实现 OperationHardcode\PhpRpcServer\Protocol\Validation\ValidateRequest
接口。在 validate
方法中,您将获得原始有效负载以确保它满足您的扩展协议规则。
use OperationHardcode\PhpRpcServer\RpcServer; use OperationHardcode\PhpRpcServer\RpcRequest; use OperationHardcode\PhpRpcServer\RpcResponse; use OperationHardcode\PhpRpcServer\Protocol\Validation\ValidateRequest; use Psr\Log\NullLogger; final class CustomValidator implements ValidateRequest { /** {@inheritdoc} */ public function validate(array $payload): bool { return false; } } $server = RpcServer::new([ 'users.get' => function (RpcRequest $request, ?RpcResponse $response = null): ?RpcResponse { return $response?->addResult([10, 11]); } ], new NullLogger(), [new CustomValidator()]) $server->process('{"jsonrpc": "2.0", "method": "users.get", "id": 1}');
如果您的验证器失败,将返回错误 INVALID_REQUEST
给客户端。
如果您对标准请求处理程序不满意,可以编写自己的。
use OperationHardcode\PhpRpcServer\RpcHandler; use OperationHardcode\PhpRpcServer\RpcRequest; use OperationHardcode\PhpRpcServer\RpcResponse; use OperationHardcode\PhpRpcServer\RpcServer; final class YourOwnRpcHandler implements RpcHandler { public function handle(RpcRequest $request, ?RpcResponse $response = null) : ?RpcResponse { // } } $server = new RpcServer(new YourOwnRpcHandler()); $server->process('{"jsonrpc": "2.0", "method": "users.get", "id": 1}');
示例
更详细的代码示例位于 examples
目录中。
测试
$ composer test
统计分析
$ composer lint
许可证
MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件。