Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Rpc Laravel Package

datto/json-rpc

Lightweight PHP library for building and parsing JSON-RPC 2.0 messages. Fully spec compliant, 100% unit-tested, and transport-agnostic so you can use HTTP, SSH, or any channel. Includes simple Client/Server APIs and working examples.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require datto/json-rpc
    
  2. Basic Client Usage:

    use Datto\JsonRpc\Client;
    
    $client = new Client();
    $response = $client->query(1, 'add', [1, 2])->encode();
    // Returns: {"jsonrpc":"2.0","method":"add","params":[1,2],"id":1}
    
  3. Basic Server Usage:

    use Datto\JsonRpc\Api;
    use Datto\JsonRpc\Server;
    
    $api = new Api();
    $api->addMethod('add', function ($params) {
        return array_sum($params);
    });
    
    $server = new Server($api);
    $reply = $server->reply('{"jsonrpc":"2.0","method":"add","params":[1,2],"id":1}');
    // Returns: {"jsonrpc":"2.0","result":3,"id":1}
    

First Use Case: REST API Wrapper

Use this package to wrap legacy REST APIs or microservices into a JSON-RPC interface:

$client = new Client();
$response = $client->query(1, 'fetchUser', ['userId' => 123])->encode();

Implementation Patterns

Client-Side Workflows

  1. Chaining Methods:

    $client->query(1, 'add', [1, 2])->encode()->sendOverHttp();
    
  2. Batch Requests:

    $client->query(1, 'method1', [])->query(2, 'method2', []);
    $batch = $client->encode();
    
  3. Custom Encoding/Decoding:

    $client->preEncode(function ($message) {
        // Modify message before encoding
        return $message;
    });
    
    $client->postDecode(function ($response) {
        // Process response after decoding
        return $response;
    });
    

Server-Side Patterns

  1. Dynamic Method Registration:

    $api = new Api();
    $api->addMethod('dynamicMethod', function ($params) {
        return "Processed: " . json_encode($params);
    });
    
  2. Error Handling:

    $api->addMethod('divide', function ($params) {
        if ($params[1] === 0) {
            throw new \Exception("Division by zero");
        }
        return $params[0] / $params[1];
    });
    
  3. Middleware for Requests:

    $server = new Server($api);
    $server->setMiddleware(function ($request) {
        // Log or validate request
        return $request;
    });
    

Integration with Laravel

  1. Route Handling:

    Route::post('/jsonrpc', function (Request $request) {
        $api = new Api();
        $api->addMethod('laravelMethod', function () {
            return ['data' => 'from Laravel'];
        });
        $server = new Server($api);
        return response()->json($server->reply($request->getContent()));
    });
    
  2. Service Container Binding:

    $app->bind('jsonrpc.api', function () {
        $api = new Api();
        $api->addMethod('appMethod', function () {
            return app('someService')->doSomething();
        });
        return $api;
    });
    

Gotchas and Tips

Common Pitfalls

  1. Transport Layer Missing: The package only handles serialization/deserialization. You must implement your own transport (HTTP, SSH, etc.) or use a companion package like datto/json-rpc-http.

  2. ID Handling:

    • Client-side IDs must be unique per request (even in batches).
    • Server-side replies must include the original ID for proper client matching.
  3. Notify vs Query:

    • notify() methods do not expect a response (no ID required).
    • query() methods require an ID and expect a response.
  4. Error Responses:

    • The decode() method returns ErrorResponse or ResultResponse objects.
    • Always check response type:
      if ($response instanceof ErrorResponse) {
          throw new \Exception($response->getMessage());
      }
      

Debugging Tips

  1. Validate JSON-RPC Input: Use Client::decode() to validate raw JSON-RPC strings before processing:

    try {
        $responses = $client->decode($rawJsonRpc);
    } catch (ErrorException $e) {
        // Invalid JSON-RPC input
    }
    
  2. Inspect Raw Messages: Use preEncode/postDecode to log or inspect messages:

    $client->preEncode(function ($message) {
        \Log::debug('Outgoing RPC:', ['message' => $message]);
        return $message;
    });
    
  3. Batch Request Quirks:

    • Batch requests must be an array of valid JSON-RPC objects.
    • The server processes each request independently (no shared state).

Extension Points

  1. Custom Response Classes: Extend Response, ResultResponse, or ErrorResponse to add metadata:

    class CustomResponse extends ResultResponse {
        public function getMetadata() {
            return $this->metadata ?? [];
        }
    }
    
  2. Transport Abstraction: Use Client::rawReply() and Server::rawReply() to integrate with custom transports:

    $client->rawReply($rawResponse); // Bypass default decoding
    
  3. Middleware for Servers: Override Server::reply() to add cross-cutting concerns (auth, logging):

    $server->setMiddleware(function ($request) {
        if (!auth()->check()) {
            throw new \Exception("Unauthorized");
        }
        return $request;
    });
    

Laravel-Specific Quirks

  1. CSRF Protection: JSON-RPC endpoints may conflict with Laravel’s CSRF middleware. Exclude them:

    Route::post('/jsonrpc', function () { ... })->middleware('jsonrpc');
    

    (Create a custom middleware to bypass CSRF.)

  2. Request Parsing: Laravel’s Request object may not parse raw JSON-RPC payloads correctly. Use:

    $rawPayload = $request->getContent();
    $responses = $client->decode($rawPayload);
    
  3. Service Container Conflicts: Avoid naming collisions with Laravel’s container bindings (e.g., api is a reserved key). Use:

    $app->bind('jsonrpc.api', function () { ... });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky