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

Rpc Server Bundle Laravel Package

bankiru/rpc-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bankiru/rpc-server-bundle
    

    Add to config/app.php under providers:

    Bankiru\RpcServerBundle\BankiruRpcServerBundle::class,
    

    Register the bundle in config/bundles.php (Symfony 4+):

    return [
        // ...
        Bankiru\RpcServerBundle\BankiruRpcServerBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Define a controller extending Bankiru\RpcServerBundle\Controller\RpcController:

    namespace App\Controller;
    
    use Bankiru\RpcServerBundle\Controller\RpcController;
    use Symfony\Component\HttpFoundation\Request;
    
    class MyRpcController extends RpcController
    {
        public function indexAction(Request $request)
        {
            $method = $request->query->get('method');
            $params = $request->query->get('params');
    
            return $this->handleRpcRequest($method, $params);
        }
    }
    

    Route it in routes.yaml:

    rpc:
        path: /api/rpc
        controller: App\Controller\MyRpcController::indexAction
    
  3. First Request: Send a JSON-RPC request via HTTP:

    curl -X POST http://your-app/api/rpc \
         -H "Content-Type: application/json" \
         -d '{"jsonrpc":"2.0","method":"myMethod","params":{"key":"value"},"id":1}'
    

Implementation Patterns

Core Workflow

  1. Request Handling:

    • Extend RpcController and override handleRpcRequest() to define custom logic.
    • Use $request->getContent() to parse incoming JSON/XML payloads.
    • Validate input with JsonSchema or manual checks.
  2. Method Routing:

    • Map HTTP routes to RPC methods dynamically (e.g., /api/rpc?method=foo).
    • Example:
      public function handleRpcRequest($method, $params)
      {
          switch ($method) {
              case 'getUser':
                  return $this->getUser($params['id']);
              case 'createOrder':
                  return $this->createOrder($params);
              default:
                  throw new \RuntimeException('Method not found');
          }
      }
      
  3. Response Formatting:

    • Return standardized RPC responses:
      return [
          'jsonrpc' => '2.0',
          'result'  => $data,
          'id'      => $request->get('id'),
      ];
      
    • Handle errors with:
      return [
          'jsonrpc' => '2.0',
          'error'   => [
              'code'    => -32601,
              'message' => 'Method not found',
          ],
          'id'      => $request->get('id'),
      ];
      
  4. Integration with Laravel Services:

    • Inject Laravel services (e.g., UserRepository) into the controller:
      public function __construct(private UserRepository $users) {}
      
      public function getUser($id) {
          return $this->users->find($id);
      }
      
  5. Middleware Integration:

    • Apply Laravel middleware (e.g., auth, CORS) to RPC routes:
      Route::middleware(['auth:sanctum'])->post('/api/rpc', [MyRpcController::class, 'index']);
      

Gotchas and Tips

Pitfalls

  1. Deprecation Risk:

    • Last release in 2016—assume no active maintenance. Test thoroughly and consider forking if critical.
    • Example: JSON-RPC 2.0 support may lack modern features (e.g., batched requests).
  2. No Built-in Validation:

    • Manually validate $method and $params to avoid injection risks:
      if (!is_string($method) || empty($method)) {
          throw new \InvalidArgumentException('Invalid method');
      }
      
  3. HTTP vs. RPC Mismatch:

    • The bundle treats RPC over HTTP, but lacks native support for:
      • Binary protocols (e.g., gRPC).
      • WebSocket upgrades (requires custom middleware).
    • Workaround: Use Symfony’s StreamedResponse for large payloads.
  4. Configuration Quirks:

    • No default config file—expect minimal setup. Override behavior via:
      $this->setRpcNamespace('App\\Rpc'); // Custom namespace for methods.
      

Debugging

  1. Logging:

    • Log raw requests/responses for debugging:
      \Log::debug('RPC Request', ['method' => $method, 'params' => $params]);
      
  2. Error Handling:

    • Catch exceptions and format them as RPC errors:
      try {
          return $this->getUser($id);
      } catch (\Exception $e) {
          return [
              'error' => ['code' => -32000, 'message' => $e->getMessage()],
          ];
      }
      
  3. Testing:

    • Mock RpcController in PHPUnit:
      $controller = $this->getMockBuilder(MyRpcController::class)
          ->onlyMethods(['getUser'])
          ->getMock();
      $controller->method('getUser')->willReturn(['id' => 1]);
      

Extension Points

  1. Custom Protocols:

    • Extend Bankiru\RpcServerBundle\Rpc\RpcInterface to support SOAP/XML-RPC:
      class CustomRpcProtocol implements RpcInterface {
          public function parse(Request $request) { /* ... */ }
          public function format($data) { /* ... */ }
      }
      
  2. Authentication:

    • Add auth logic in handleRpcRequest():
      if (!$this->isAuthenticated($request)) {
          throw new \RuntimeException('Unauthorized');
      }
      
  3. Performance:

    • Cache frequent RPC responses (e.g., getUser):
      $cacheKey = "rpc_user_{$id}";
      return Cache::remember($cacheKey, 3600, function() use ($id) {
          return $this->users->find($id);
      });
      
  4. Documentation:

    • Use OpenAPI/Swagger annotations to document RPC methods:
      /**
       * @OA\Post(
       *     path="/api/rpc",
       *     summary="Get user by ID",
       *     @OA\RequestBody(
       *         required=true,
       *         @OA\JsonContent(ref="#/components/schemas/RpcRequest")
       *     )
       * )
       */
      
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