procurios/json-rpc

PHP 的 JSON-RPC 2.0 服务器

v2.0.0 2023-09-08 14:35 UTC

This package is auto-updated.

Last update: 2024-09-08 17:07:19 UTC


README

Build Status Coverage Status

服务器

服务器是完全符合 JSON-RPC 2.0 规范 的实现。服务器将公开对象或静态类的公共方法,这些方法可以通过接口或特定的父类进行限制(可选)。

为了鼓励接口分离,不支持其他方法,如闭包或全局函数。

特性

  • 完整规范,包括通知、按名称和按位置传递参数以及批处理请求
  • 跳过的参数使用默认值
  • 支持可变参数
  • PSR-7 兼容:此服务器可以直接处理 Psr\Http\Message\ServerRequestInterface 的实现,返回 Psr\Http\Message\ResponseInterface 的实现,如 PSR-7 中定义

要求

PHP >= 8.0

示例

主题类

MyInterface

<?php
interface MyInterface
{
    public function foo();
}

MySubjectClass

<?php
class MySubjectClass implements MyInterface
{
    public function foo()
    {
        return 'foo';
    }

    public function bar()
    {
        return 'bar';
    }
}

直接处理请求

<?php
use Procurios\Json\JsonRpc\Server;
use Procurios\Json\JsonRpc\Request\Request;

$requestData = json_decode(file_get_contents('php://input'), true);
$Request = Request::fromArray($requestData);

$Server = new Server(new MySubjectClass);
$Response = $Server->handleRequest($Request);

header('Content-Type: application/json');
die($Response->asString());

处理 PSR-7 ServerRequestInterface

<?php
use Procurios\Json\JsonRpc\Server;

$Server = new Server(new MySubjectClass);

// Use the current Psr\Http\Message\ServerRequestInterface implementation in your application
$Request = MyRequestSource::getRequest();

// Create an empty implementation of Psr\Http\Message\ResponseInterface
$BaseResponse = MyResponseFactory::createResponse();

$Response = $Server->handleServerRequest($Request, $BaseResponse);

MyResponseEmitter::emit($Response);

限制主题为接口

<?php
use Procurios\Json\JsonRpc\Server;

$Server = new Server(new MySubjectClass, MyInterface::class);

// Only the method foo will be available in this server, since bar is not part of the interface