fguillot/json-rpc 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

fguillot/json-rpc

Composer 安装命令:

composer require fguillot/json-rpc

包简介

Simple JSON-RPC client/server library that just works

README 文档

README

CI workflow

A simple JSON-RPC client/server that just works.

Features

  • JSON-RPC 2.0 only
  • The server support batch requests and notifications
  • Authentication and IP based client restrictions
  • Custom Middleware
  • Fully unit tested
  • License: MIT

Contributors

Frédéric Guillot and many others:

Contributors

Installation with Composer

composer require fguillot/json-rpc

Examples

Symfony

Server

Callback binding:

<?php

use JsonRPC\Server;

$server = new Server();
$server->getProcedureHandler()
    ->withCallback('addition', function ($a, $b) {
        return $a + $b;
    })
    ->withCallback('random', function ($start, $end) {
        return mt_rand($start, $end);
    })
;

echo $server->execute();

Callback binding from array:

<?php

use JsonRPC\Server;

$callbacks = [
    'getA' => function() { return 'A'; },
    'getB' => function() { return 'B'; },
    'getC' => function() { return 'C'; }
];

$server = new Server();
$server->getProcedureHandler()->withCallbackArray($callbacks);

echo $server->execute();

Class/Method binding:

<?php

use JsonRPC\Server;

class Api
{
    public function doSomething($arg1, $arg2 = 3)
    {
        return $arg1 + $arg2;
    }
}

$server = new Server();
$procedureHandler = $server->getProcedureHandler();

// Bind the method Api::doSomething() to the procedure myProcedure
$procedureHandler->withClassAndMethod('myProcedure', 'Api', 'doSomething');

// Use a class instance instead of the class name
$procedureHandler->withClassAndMethod('mySecondProcedure', new Api, 'doSomething');

// The procedure and the method are the same
$procedureHandler->withClassAndMethod('doSomething', 'Api');

// Attach the class, the client will be able to call directly Api::doSomething()
$procedureHandler->withObject(new Api());

echo $server->execute();

Class/Method binding from array:

<?php

use JsonRPC\Server;

class MathApi
{
    public function addition($arg1, $arg2)
    {
        return $arg1 + $arg2;
    }

    public function subtraction($arg1, $arg2)
    {
        return $arg1 - $arg2;
    }

    public function multiplication($arg1, $arg2)
    {
        return $arg1 * $arg2;
    }

    public function division($arg1, $arg2)
    {
        return $arg1 / $arg2;
    }
}

$callbacks = [
    'addition'       => [ 'MathApi', addition ],
    'subtraction'    => [ 'MathApi', subtraction ],
    'multiplication' => [ 'MathApi', multiplication ,
    'division'       => [ 'MathApi', division ],
];

$server = new Server();
$server->getProcedureHandler()->withClassAndMethodArray($callbacks);

echo $server->execute();

Server Middleware:

Middleware might be used to authenticate and authorize the client. They are executed before each procedure.

<?php

use JsonRPC\Server;
use JsonRPC\MiddlewareInterface;
use JsonRPC\Exception\AuthenticationFailureException;

class Api
{
    public function doSomething($arg1, $arg2 = 3)
    {
        return $arg1 + $arg2;
    }
}

class MyMiddleware implements MiddlewareInterface
{
    public function execute($username, $password, $procedureName)
    {
        if ($username !== 'foobar') {
            throw new AuthenticationFailureException('Wrong credentials!');
        }
    }
}

$server = new Server();
$server->getMiddlewareHandler()->withMiddleware(new MyMiddleware());
$server->getProcedureHandler()->withObject(new Api());
echo $server->execute();

You can raise a AuthenticationFailureException when the API credentials are wrong or a AccessDeniedException when the user is not allowed to access to the procedure.

Client

Example with positional parameters:

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');
$result = $client->execute('addition', [3, 5]);

Example with named arguments:

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');
$result = $client->execute('random', ['end' => 10, 'start' => 1]);

Arguments are called in the right order.

Examples with the magic method __call():

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');
$result = $client->random(50, 100);

The example above use positional arguments for the request and this one use named arguments:

$result = $client->random(['end' => 10, 'start' => 1]);

Client batch requests

Call several procedures in a single HTTP request:

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');

$results = $client->batch()
                  ->foo(['arg1' => 'bar'])
                  ->random(1, 100)
                  ->add(4, 3)
                  ->execute('add', [2, 5])
                  ->send();

print_r($results);

All results are stored at the same position of the call.

Client exceptions

Client exceptions are normally thrown when an error is returned by the server. You can change this behaviour by using the $returnException argument which causes exceptions to be returned. This can be extremely useful when executing the batch request.

  • BadFunctionCallException: Procedure not found on the server
  • InvalidArgumentException: Wrong procedure arguments
  • JsonRPC\Exception\AccessDeniedException: Access denied
  • JsonRPC\Exception\ConnectionFailureException: Connection failure
  • JsonRPC\Exception\ServerErrorException: Internal server error

Enable client debugging

You can enable the debug mode to see the JSON request and response:

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');
$client->getHttpClient()->withDebug();

The debug output is sent to the PHP system logger. You can configure the log destination in your php.ini.

Output example:

==> Request:
{
    "jsonrpc": "2.0",
    "method": "removeCategory",
    "id": 486782327,
    "params": [
        1
    ]
}
==> Response:
{
    "jsonrpc": "2.0",
    "id": 486782327,
    "result": true
}

IP based client restrictions

The server can allow only some IP addresses:

<?php

use JsonRPC\Server;

$server = new Server;

// IP client restrictions
$server->allowHosts(['192.168.0.1', '127.0.0.1']);

...

// Return the response to the client
echo $server->execute();

If the client is blocked, you got a 403 Forbidden HTTP response.

HTTP Basic Authentication

If you use HTTPS, you can allow client by using a username/password.

<?php

use JsonRPC\Server;

$server = new Server;

// List of users to allow
$server->authentication(['user1' => 'password1', 'user2' => 'password2']);

...

// Return the response to the client
echo $server->execute();

On the client, set credentials like that:

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');
$client->getHttpClient()
    ->withUsername('Foo')
    ->withPassword('Bar');

If the authentication failed, the client throw a RuntimeException.

Using an alternative authentication header:

use JsonRPC\Server;

$server = new Server();
$server->setAuthenticationHeader('X-Authentication');
$server->authentication(['myusername' => 'mypassword']);

The example above will use the HTTP header X-Authentication instead of the standard Authorization: Basic [BASE64_CREDENTIALS]. The username/password values need be encoded in base64: base64_encode('username:password').

Local Exceptions

By default, the server will relay all exceptions to the client. If you would like to relay only some of them, use the method Server::withLocalException($exception):

<?php

use JsonRPC\Server;
class MyException1 extends Exception {};
class MyException2 extends Exception {};

$server = new Server();

// Exceptions that should NOT be relayed to the client, if they occurs
$server
    ->withLocalException('MyException1')
    ->withLocalException('MyException2')
;

...

echo $server->execute();

Callback before client request

You can use a callback to change the HTTP headers or the URL before to make the request to the server.

Example:

<?php

$client = new Client();
$client->getHttpClient()->withBeforeRequestCallback(function(HttpClient $client, $payload) {
    $client->withHeaders(['Content-Length: '.strlen($payload)]);
});

$client->myProcedure(123);

fguillot/json-rpc 适用场景与选型建议

fguillot/json-rpc 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 752.13k 次下载、GitHub Stars 达 23, 最近一次更新时间为 2018 年 10 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 fguillot/json-rpc 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 fguillot/json-rpc 我们能提供哪些服务?
定制开发 / 二次开发

基于 fguillot/json-rpc 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 752.13k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 25
  • 点击次数: 8
  • 依赖项目数: 26
  • 推荐数: 0

GitHub 信息

  • Stars: 23
  • Watchers: 3
  • Forks: 151
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-10-06