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

Jsonrpc Server Bundle Laravel Package

bankiru/jsonrpc-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bankiru/jsonrpc-server-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Bankiru\JsonRpcServerBundle\BankiruJsonRpcServerBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Edit config/packages/bankiru_json_rpc_server.yaml:

    bankiru_json_rpc_server:
        routes:
            jsonrpc: /api/jsonrpc
    
  3. First Endpoint Create a service to handle RPC calls:

    // src/Service/MyRpcService.php
    namespace App\Service;
    
    use Bankiru\RpcServerBundle\Annotation\RpcMethod;
    
    class MyRpcService
    {
        /**
         * @RpcMethod("add")
         */
        public function add(int $a, int $b): int
        {
            return $a + $b;
        }
    }
    
  4. Test with cURL

    curl -X POST http://your-app/api/jsonrpc \
      -H "Content-Type: application/json" \
      -d '{"jsonrpc": "2.0", "method": "add", "params": [5, 3], "id": 1}'
    

    Expected response:

    {"jsonrpc":"2.0","result":8,"id":1}
    

Implementation Patterns

Service Integration

  1. Annotated Methods Use @RpcMethod annotation to expose methods:

    /**
     * @RpcMethod("user.create", description="Creates a new user")
     * @RpcMethod("user.update", description="Updates an existing user")
     */
    public function handleUser($action, array $data)
    {
        // Logic here
    }
    
  2. Dependency Injection Inject services into RPC handlers:

    public function __construct(private UserRepository $userRepo) {}
    
    /**
     * @RpcMethod("user.get")
     */
    public function getUser(int $id): array
    {
        return $this->userRepo->find($id);
    }
    
  3. Request/Response Handling Access raw request/response via events:

    // src/EventListener/RpcListener.php
    use Bankiru\JsonRpcServerBundle\Event\JsonRpcEvent;
    
    public function onJsonRpc(JsonRpcEvent $event)
    {
        $request = $event->getRequest();
        $response = $event->getResponse();
    }
    

Routing and Middleware

  1. Custom Routes Override default route in config:

    bankiru_json_rpc_server:
        routes:
            jsonrpc: /v1/rpc
    
  2. Authentication Use Symfony middleware (e.g., ApiKeyAuthenticator):

    # config/packages/security.yaml
    security:
        firewalls:
            jsonrpc:
                pattern: ^/api/jsonrpc
                stateless: true
                json_login:
                    check_path: /api/jsonrpc/login
    
  3. CORS Configuration Add to config/packages/nelmio_cors.yaml:

    nelmio_cors:
        defaults:
            allow_origin: ["*"]
        paths:
            '^/api/jsonrpc':
                allow_origin: ["*"]
                allow_methods: ["POST"]
                allow_headers: ["Content-Type"]
                max_age: 3600
    

Error Handling

  1. Custom Errors Throw exceptions with specific codes:

    throw new \RuntimeException("Invalid input", 1001);
    

    Map to JSON-RPC errors via event subscriber:

    public function onJsonRpcError(JsonRpcErrorEvent $event)
    {
        $event->setErrorCode(1001);
        $event->setErrorMessage("Custom error message");
    }
    
  2. Validation Use Symfony Validator:

    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @RpcMethod("user.create")
     * @param array $data {
     *     @Assert\NotBlank()
     *     string name
     * }
     */
    public function createUser(array $data)
    {
        // ...
    }
    

Gotchas and Tips

Common Pitfalls

  1. Annotation Parsing

    • Issue: @RpcMethod not recognized.
    • Fix: Ensure bankiru/rpc-server-bundle is installed and autoloaded.
      composer require bankiru/rpc-server-bundle
      
    • Debug: Clear cache:
      php bin/console cache:clear
      
  2. Serialization Conflicts

    • Issue: Responses not serialized correctly.
    • Fix: Subscribe to rpc.view event:
      public function onRpcView(RpcViewEvent $event)
      {
          $event->setData(json_encode($event->getData()));
      }
      
  3. Circular References

    • Issue: JSON-RPC responses fail with "Maximum function nesting level".
    • Fix: Use JsonSerializable or custom serializer:
      class User implements JsonSerializable
      {
          public function jsonSerialize()
          {
              return ['id' => $this->id, 'name' => $this->name];
          }
      }
      
  4. Deprecated Methods

    • Issue: JsonRpcRequestInterface not found.
    • Fix: Use Bankiru\RpcServerBundle\Request\JsonRpcRequest instead.

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        json_rpc:
            type: stream
            path: "%kernel.logs_dir%/jsonrpc.log"
            level: debug
            channels: ["json_rpc"]
    
  2. Inspect Events Dump events in a subscriber:

    public function onJsonRpc(JsonRpcEvent $event)
    {
        \Symfony\Component\Debug\Debug::dump($event->getRequest()->getContent());
    }
    
  3. Test with Postman Use Postman to send raw JSON-RPC requests and inspect responses.

Extension Points

  1. Custom Serializers Override default JSON serializer:

    // src/Serializer/CustomJsonSerializer.php
    use Bankiru\JsonRpcServerBundle\Serializer\JsonSerializerInterface;
    
    class CustomJsonSerializer implements JsonSerializerInterface
    {
        public function serialize($data)
        {
            return json_encode($data, JSON_PRETTY_PRINT);
        }
    }
    

    Register as service:

    services:
        Bankiru\JsonRpcServerBundle\Serializer\JsonSerializerInterface: '@App\Serializer\CustomJsonSerializer'
    
  2. Dynamic Method Loading Use RpcMethodLoaderInterface to load methods dynamically:

    public function loadMethods()
    {
        return [
            'dynamic.method' => [$this, 'handleDynamicMethod'],
        ];
    }
    
  3. Middleware Stack Add custom middleware:

    // src/Middleware/RpcLoggingMiddleware.php
    use Bankiru\JsonRpcServerBundle\Middleware\RpcMiddlewareInterface;
    
    class RpcLoggingMiddleware implements RpcMiddlewareInterface
    {
        public function handle(JsonRpcRequest $request, callable $next)
        {
            // Pre-processing
            $response = $next($request);
            // Post-processing
            return $response;
        }
    }
    

    Register in config:

    bankiru_json_rpc_server:
        middleware:
            - App\Middleware\RpcLoggingMiddleware
    

Performance Considerations

  1. Caching RPC Methods Cache method metadata to avoid repeated annotation parsing:

    // src/Cache/RpcMethodCache.php
    use Doctrine\Common\Cache\CacheProvider;
    
    class RpcMethodCache implements CacheProvider
    {
        public function fetch($id)
        {
            // Implement caching logic
        }
    }
    

    Configure in config/packages/bankiru_json_rpc_server.yaml:

    bankiru_json_rpc_server:
        cache: App\Cache\RpcMethodCache
    
  2. Batch Processing Handle batch requests efficiently:

    /**
     * @RpcMethod("batch.process")
     */
    public function processBatch(array $operations)
    {
        $results = [];
        foreach ($operations as $op) {
            $results[] = $this->executeOperation($op);
        }
        return $results;
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui