wwtg99 / jsonrpc
该包最新版本(0.2.2)没有可用的许可证信息。
0.2.2
2017-12-07 06:17 UTC
Requires
- guzzlehttp/guzzle: ~6.0
Requires (Dev)
- laravel/framework: 5.4.*
- phpunit/phpunit: ~5.7
This package is not auto-updated.
Last update: 2024-09-24 09:41:21 UTC
README
JSON-RPC 2.0 服务器和客户端,为 Laravel 实现了 JSON-RPC 2.0。
功能
- 仅支持 JSON-RPC 2.0
- 支持批量请求和通知
- 对 Laravel 简单易用
- 需要 PHP >= 5.6 和 GuzzleHttp >= 6.0
- 许可证: MIT
JSON-RPC 规范
安装
composer require wwtg99/jsonrpc
对于 Lumen 或 v5.5 之前的 Laravel,您需要手动注册服务提供者和别名,
Wwtg99\JsonRpc\Provider\JsonRpcServiceProvider::class
'JsonRpc' => Wwtg99\JsonRpc\Facades\JsonRpc::class
使用方法
服务器端
绑定方法
绑定回调
JsonRpc::bind('method1', function($request) { $method = $request->getMethod(); $params = $request->getParams(); $p = $request->parseParam('name'); //get param name $id = $request->getId(); //some process... //return result array, request id will be added automatically return [1, 2, 3]; //Or use JsonRpcResponse return new JsonRpcResponse($id, [1, 2, 3]); //return error return new JsonRpcResponse($id, null, ['code'=>1, 'message'=>'error']); }); // Or use handler instance $ph = resolve('ProcessHandler'); $ph->bind('method1', function($request) { return [1, 2, 3]; });
绑定类方法
namespace Test; class BindingTest { public function test1($request) { return [1, 2, 3]; } } JsonRpc::bind('method2', 'Test\BindingTest@test1'); // Or $ph->bind('method2', 'Test\BindingTest@test1');
处理请求
添加路由
//you should disable VerifyCsrfToken middleware if use post method Route::match(['GET', 'POST'], '/json_rpc', function() { $res = JsonRpc::parse(request()); //other process return response()->json($res); });
或者简单使用
Route::match(['GET', 'POST'], '/json_rpc', function (\Illuminate\Http\Request $request) { return Wwtg99\JsonRpc\Provider\JsonRpcRouter::parse($request); });
客户端
在客户端发送请求
第一个参数是 json rpc 服务器 URL,第二个参数是配置选项。
选项
- http_method: 发送请求的 http 方法,get 或 post,默认 post
- return_type: 响应的返回类型,json 或 string,默认 json
其他选项将被发送到 Guzzle 客户端。
//get client $cli = new JsonRpcClient($url); //default method is post, return type json //use get method //$cli = new JsonRpcClient($url, ['http_method'=>'get']); //use raw string return instead of json //$cli = new JsonRpcClient($url, ['return_type'=>'string']); //build requests $req1 = new JsonRpcRequest('method1', 1, [1, 2, 3]); $req1 = new JsonRpcRequest('method1', 2, [1, 2, 3]); //send one request $res = $cli->send($req1); //send batch requests $res = $cli->appendRequest($req1)->appendRequest($req2)->send(); //send notify $cli->notify('method2', ['a'=>'b'])