PHPackages                             tourze/json-rpc-core - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. tourze/json-rpc-core

ActiveLibrary[API Development](/categories/api)

tourze/json-rpc-core
====================

JSON-RPC 2.0 Core

2.0.0(4mo ago)017.5k20MITPHPCI passing

Since Apr 12Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/json-rpc-core)[ Packagist](https://packagist.org/packages/tourze/json-rpc-core)[ RSS](/packages/tourze-json-rpc-core/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (14)Versions (17)Used By (20)

JSON-RPC Core
=============

[](#json-rpc-core)

[![PHP Version](https://camo.githubusercontent.com/f870cee2a2e2a442c6b62c8bf79f45ec0ce794dc5af13834902518c9107230f9/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d382e312532422d626c75652e737667)](https://php.net)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](LICENSE)[![Build Status](https://camo.githubusercontent.com/c27a457659b89ee4f1f80f7995c559dd37f2051bde7167ad25791e5c5c92cc8e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c642d70617373696e672d627269676874677265656e2e737667)](#testing)[![Code Coverage](https://camo.githubusercontent.com/06e33fb4024f7f9c576cc80d22e78dbb33bd31fd8dbf978c6effb2adbf0f5087/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d39352532352d627269676874677265656e2e737667)](#testing)

[English](README.md) | [中文](README.zh-CN.md)

This library provides core components compliant with the [JSON-RPC 2.0 specification](https://www.jsonrpc.org/specification)for building JSON-RPC servers and clients in PHP.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Components](#components)
- [Usage Example](#usage-example)
- [Advanced Usage](#advanced-usage)
- [Testing](#testing)
- [License](#license)

Features
--------

[](#features)

- Fully compliant with JSON-RPC 2.0 specification
- Supports all JSON-RPC request types: single, batch, and notification
- Robust error handling for all standard JSON-RPC error types
- Flexible method resolution interfaces
- Clean object-oriented API

Installation
------------

[](#installation)

```
composer require tourze/json-rpc-core
```

**Requirements:**

- PHP 8.1+
- nesbot/carbon ^2.72 || ^3
- psr/log ^1|^2|^3
- symfony/dependency-injection ^7.3
- symfony/event-dispatcher-contracts ^3
- symfony/http-foundation ^7.3
- symfony/property-access ^7.3
- symfony/service-contracts ^3.6
- symfony/validator ^7.3
- tourze/arrayable 0.0.\*
- tourze/backtrace-helper 0.1.\*

Components
----------

[](#components)

### Models

[](#models)

- `JsonRpcRequest` - Represents a JSON-RPC request
- `JsonRpcResponse` - Represents a JSON-RPC response
- `JsonRpcParams` - Wraps request parameters
- `JsonRpcCallRequest` - Handles batch requests
- `JsonRpcCallResponse` - Handles batch responses

### Domain Interfaces

[](#domain-interfaces)

- `JsonRpcMethodInterface` - Defines the interface for JSON-RPC methods
- `JsonRpcMethodResolverInterface` - Resolves method names to implementations
- `JsonRpcMethodParamsValidatorInterface` - Validates method parameters
- `MethodWithValidatedParamsInterface` - Methods with parameter validation
- `MethodWithResultDocInterface` - Methods with result documentation

### Exceptions

[](#exceptions)

- `JsonRpcException` - Base JSON-RPC exception
- `JsonRpcParseErrorException` - Parse error exception
- `JsonRpcInvalidRequestException` - Invalid request exception
- `JsonRpcMethodNotFoundException` - Method not found exception
- `JsonRpcInvalidParamsException` - Invalid params exception
- `JsonRpcInternalErrorException` - Internal error exception

Usage Example
-------------

[](#usage-example)

### Creating a JSON-RPC Method

[](#creating-a-json-rpc-method)

```
use Tourze\JsonRPC\Core\Domain\JsonRpcMethodInterface;
use Tourze\JsonRPC\Core\Model\JsonRpcRequest;

class EchoMethod implements JsonRpcMethodInterface
{
    public function __invoke(JsonRpcRequest $request): mixed
    {
        return $request->getParams()->all();
    }

    public function execute(): array
    {
        return [];
    }
}
```

### 处理 JSON-RPC 请求

[](#处理-json-rpc-请求)

```
use Tourze\JsonRPC\Core\Exception\JsonRpcException;
use Tourze\JsonRPC\Core\Model\JsonRpcParams;
use Tourze\JsonRPC\Core\Model\JsonRpcRequest;
use Tourze\JsonRPC\Core\Model\JsonRpcResponse;

// 创建请求
$request = new JsonRpcRequest();
$request->setJsonrpc('2.0');
$request->setMethod('echo');
$request->setId('1');
$request->setParams(new JsonRpcParams(['message' => 'Hello, World!']));

// 创建方法实例
$method = new EchoMethod();

// 执行方法并获取响应
$response = new JsonRpcResponse();
$response->setJsonrpc('2.0');
$response->setId($request->getId());

try {
    $result = $method($request);
    $response->setResult($result);
} catch (JsonRpcException $e) {
    $response->setError($e);
} catch (\Throwable $e) {
    // 将普通异常包装为 JSON-RPC 异常
    $jsonRpcException = new JsonRpcException(-32000, $e->getMessage());
    $response->setError($jsonRpcException);
}
```

### 批量请求

[](#批量请求)

通过 `JsonRpcCallRequest` 和 `JsonRpcCallResponse` 处理批量请求。详见单元测试中的示例。

Advanced Usage
--------------

[](#advanced-usage)

### Custom Parameter Validation

[](#custom-parameter-validation)

Use the `BaseProcedure` class for automatic parameter validation:

```
use Tourze\JsonRPC\Core\Procedure\BaseProcedure;
use Tourze\JsonRPC\Core\Attribute\MethodParam;
use Symfony\Component\Validator\Constraints as Assert;

class CalculatorMethod extends BaseProcedure
{
    #[MethodParam('First number')]
    #[Assert\Type('numeric')]
    #[Assert\NotBlank]
    public int $a;

    #[MethodParam('Second number')]
    #[Assert\Type('numeric')]
    #[Assert\NotBlank]
    public int $b;

    public function execute(): int
    {
        return $this->a + $this->b;
    }
}
```

### Event-Driven Architecture

[](#event-driven-architecture)

Listen to JSON-RPC events for logging and monitoring:

```
use Tourze\JsonRPC\Core\Event\BeforeMethodApplyEvent;
use Tourze\JsonRPC\Core\Event\AfterMethodApplyEvent;

// Before method execution
$dispatcher->addListener(BeforeMethodApplyEvent::class, function ($event) {
    $logger->info('Method called', [
        'method' => $event->getName(),
        'params' => $event->getParams()->all()
    ]);
});

// After method execution
$dispatcher->addListener(AfterMethodApplyEvent::class, function ($event) {
    $logger->info('Method completed', [
        'method' => $event->getName(),
        'result' => $event->getResult()
    ]);
});
```

### Helper Classes for Complex Validation

[](#helper-classes-for-complex-validation)

The package includes helper classes for advanced parameter processing:

- `TypeValidatorFactory`: Creates type validators from reflection
- `PropertyConstraintExtractor`: Extracts validation constraints from properties
- `ParameterProcessor`: Handles parameter assignment and validation

Testing
-------

[](#testing)

```
vendor/bin/phpunit packages/json-rpc-core/tests
```

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance74

Regular maintenance activity

Popularity20

Limited adoption so far

Community22

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~16 days

Total

16

Last Release

144d ago

Major Versions

0.0.9 → 1.0.02025-10-31

1.0.5 → 2.0.02025-12-19

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (3 commits)")

---

Tags

jsonrpc

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-json-rpc-core/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-json-rpc-core/health.svg)](https://phpackages.com/packages/tourze-json-rpc-core)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6939.5M343](/packages/drupal-core-recommended)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
