Search by

n-car / rpc-php-toolkit

n-car

PHP JSON-RPC 2.0 client/server toolkit with middleware, schema validation, batch processing, introspection, and optional Safe Mode

Package info

github.com/n-car/rpc-php-toolkit

pkg:composer/n-car/rpc-php-toolkit

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v2.0.1 2026-10-12 16:52 UTC

This package is auto-updated.

Last update: 2026-10-30 10:58:37 UTC


README

CI Packagist Version Packagist Downloads PHP Version License Status

PHP JSON-RPC 2.0 client/server toolkit with middleware, schema validation, batch processing, introspection, and optional RPC Toolkit Safe Mode.

Use this package when you need a PHP JSON-RPC endpoint, a PHP HTTP client, or a PHP runtime that interoperates with the broader RPC Toolkit ecosystem.

Version 2.0.1 aligns JSON-RPC container and notification handling while retaining trusted-context protection. See the release notes; available package versions are listed on Packagist and the release page.

Standard First

Standard JSON-RPC 2.0 is the default behavior. Enable RPC Toolkit Safe Mode only when both sides are compatible endpoints and need type-aware round-tripping for marker-like strings, dates, and large integer markers.

Installation

With Composer (recommended)

Install the package from Packagist:

composer require n-car/rpc-php-toolkit

Composer installs the package, configures autoloading, and makes future updates straightforward.

Without Composer

Composer is not required at runtime. Download the source archive from the latest release, extract it into your project (for example as lib/rpc-php-toolkit), and load the bundled autoloader:

require_once __DIR__ . '/lib/rpc-php-toolkit/autoload.php';

When installing manually, update the library by replacing that directory with the contents of a newer release archive.

Runtime requirements:

  • PHP 8.0 or newer
  • JSON and mbstring PHP extensions
  • pdo_mysql only when using MySqlRateLimitStore

Quick Start

<?php
// Composer installation:
require_once __DIR__ . '/vendor/autoload.php';

// Manual installation: use this instead of the line above.
// require_once __DIR__ . '/lib/rpc-php-toolkit/autoload.php';

use RpcPhpToolkit\RpcEndpoint;

$rpc = new RpcEndpoint('/api/rpc');

$rpc->addMethod('getTime', function($params, $context) {
    return [
        'timestamp' => time(),
        'datetime' => date('c')
    ];
});

$rpc->addMethod('echo', function($params, $context) {
    return ['message' => $params['message'] ?? 'Hello World'];
});

$input = file_get_contents('php://input');
echo $rpc->handleRequest($input);

The endpoint assumes production when APP_ENV is not set. Batch requests, introspection, and wildcard CORS are disabled by default in production. Enable features explicitly after reviewing their exposure:

$rpc = new RpcEndpoint('/api/rpc', $context, [
    'environment' => 'production',
    'enableBatch' => false,
    'enableIntrospection' => false,
]);

Handler calling convention

Version 2 uses paramsMode: named by default. This option names the PHP calling convention, not a restriction on the JSON-RPC parameter container: the callback receives the complete object or array as one PHP array, followed by trusted server context. Empty {}, omitted parameters, and an empty [] all reach the handler as []; schema validation still distinguishes an object from an array on the wire. Explicit params: null is invalid; omit params or send {} / [] for an empty call:

$rpc->addMethod('sumArray', function (array $params, array $context) {
    return array_sum($params);
});
// JSON-RPC params: [1, 2, 3] -> result: 6; context always comes from the server.

Only handlers that need separate PHP arguments must opt in to positional spreading:

$rpc->addMethod('sum', function (int $a, int $b, array $context) {
    return $a + $b;
}, ['paramsMode' => RpcEndpoint::PARAMS_MODE_POSITIONAL]);

A positional callback must declare its final parameter for server context; clients send only the preceding arguments. Extra arguments and variadic handlers are rejected, and omitted optional arguments use their declared defaults. Set paramsMode in endpoint options to change its default, or override it per method. Existing handlers that relied on automatic array spreading must opt in explicitly; request data no longer selects the PHP calling convention.

Nested empty JSON objects and objects whose numeric keys would form a PHP list are preserved as stdClass; ordinary objects still use associative arrays. This keeps {} distinct from [] in payloads and Safe Mode. Handlers returning an empty object explicitly should return (object) [], not []. The outer callback parameter container remains a PHP array for compatibility: return (object) $params when a method intentionally returns that container as a JSON object, including when it is empty or has numeric property names.

On the wire, an absent id is a notification; an explicit id: null receives a response. Invalid envelopes (including scalar/null params) return -32600 with id: null; malformed JSON returns -32700. Method-level parameter errors remain -32602. Explicit application error data is preserved; internal errors remain sanitized by default.

PHP Client

use RpcPhpToolkit\Client\RpcClient;

$client = new RpcClient('http://localhost:8000/api/rpc');

$time = $client->call('getTime');
$echo = $client->call('echo', ['message' => 'Hello']);

$results = $client->batch([
    ['method' => 'getTime', 'id' => 1],
    ['method' => 'echo', 'params' => ['message' => 'Batch'], 'id' => 2],
]);

$client->notify('log.event', ['source' => 'php-client']);

Key Capabilities

  • JSON-RPC 2.0 calls, notifications, and batch requests
  • PHP endpoint and PHP HTTP client
  • Middleware for CORS, Bearer authentication, persistent rate limiting, and custom request processing
  • Schema validation for method parameters
  • Optional introspection through __rpc.* methods
  • Optional RPC Toolkit Safe Mode over HTTP headers
  • Structured logging hooks and configurable error sanitization

Advanced Documentation

  • Clients - PHP client, Safe client, batch calls, notifications, and browser/Node.js client notes.
  • Schema Validation - method parameter schemas and validation errors.
  • Introspection - __rpc.listMethods, __rpc.describe, __rpc.describeAll, __rpc.version, and __rpc.capabilities.
  • Middleware - CORS, authentication, rate limiting, and custom middleware.
  • Safe Mode - optional type-aware serialization, headers, marker behavior, and PHP type notes.
  • Security - production hardening notes for validation, authentication, CORS, errors, and TLS.

Examples

The examples/ folder contains runnable PHP and cross-runtime examples:

Examples demonstrating the container, error, and notification fixes require version 2.0.1 or newer, or a matching source checkout.

Quick local server:

cd examples
php -S localhost:8000 basic-server.php

Related Packages

License

MIT. See LICENSE.