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

Symfony4 Rpc Server Bundle Laravel Package

devim/symfony4-rpc-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Symfony 4 project via Composer:

    composer require devim/symfony4-rpc-server-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Devim\RpcServerBundle\DevimRpcServerBundle::class => ['all' => true],
    ];
    
  2. Configuration Define RPC endpoints in config/packages/devim_rpc_server.yaml:

    devim_rpc_server:
        endpoints:
            - { path: '/api/rpc', methods: ['POST'] }
    
  3. First RPC Method Create a service annotated with @RpcMethod:

    use Devim\RpcServerBundle\Annotation\RpcMethod;
    
    class MyRpcService
    {
        /**
         * @RpcMethod("add")
         */
        public function add(int $a, int $b): int
        {
            return $a + $b;
        }
    }
    

    Register the service in services.yaml:

    services:
        App\Service\MyRpcService:
            tags: ['rpc.method']
    
  4. Testing Send a POST request to /api/rpc with JSON payload:

    {
        "method": "add",
        "params": [5, 3]
    }
    

    Expected response:

    { "result": 8 }
    

Implementation Patterns

Workflow: RPC Method Development

  1. Annotation-Driven Use @RpcMethod to expose public methods as RPC endpoints. Name the method in the annotation to define the RPC callable name.

    /**
     * @RpcMethod("user.get")
     */
    public function getUser(int $id): array
    
  2. Parameter Handling

    • Type Hints: Leverage PHP type hints for automatic validation.
    • Arrays/Objects: Use array or custom DTOs for complex inputs.
      /**
       * @RpcMethod("order.create")
       */
      public function createOrder(OrderDto $order): OrderResponse
      
  3. Authentication/Authorization Integrate with Symfony’s security system via event listeners:

    # config/packages/devim_rpc_server.yaml
    devim_rpc_server:
        listeners:
            - App\EventListener\RpcAuthListener
    

    Example listener:

    class RpcAuthListener implements RpcEventSubscriberInterface
    {
        public function onRpcCall(RpcEvent $event)
        {
            if (!$event->getUser()) {
                throw new \RuntimeException('Unauthorized');
            }
        }
    }
    
  4. Error Handling Throw exceptions (e.g., RpcException) for custom error responses:

    public function deleteUser(int $id): void
    {
        if (!$this->userRepository->exists($id)) {
            throw new RpcException('User not found', 404);
        }
        // ...
    }
    
  5. Async Methods Use Symfony’s Messenger component for async RPC calls:

    /**
     * @RpcMethod("task.async")
     */
    public function asyncTask(string $data): void
    {
        $this->messageBus->dispatch(new AsyncTaskMessage($data));
    }
    

Integration Tips

  1. API Versioning Prefix RPC methods with version tags (e.g., @RpcMethod("v1.user.get")) and route based on path segments.

  2. Documentation Generate OpenAPI/Swagger docs by integrating with nelmio/api-doc-bundle and annotating RPC methods:

    /**
     * @RpcMethod("user.list")
     * @ApiResource()
     */
    
  3. Rate Limiting Use Symfony’s RateLimitStrategy middleware to restrict RPC calls:

    # config/packages/framework.yaml
    framework:
        http_client:
            rate_limit_strategy: Symfony\Component\HttpClient\RateLimit\RateLimitStrategy
    
  4. Logging Log RPC calls via Symfony’s logger:

    use Psr\Log\LoggerInterface;
    
    class RpcLogger implements RpcEventSubscriberInterface
    {
        public function __construct(private LoggerInterface $logger) {}
    
        public function onRpcCall(RpcEvent $event)
        {
            $this->logger->info('RPC call', [
                'method' => $event->getMethod(),
                'params' => $event->getParams(),
            ]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle

    • Last release in 2018; verify compatibility with Symfony 4.4+ (may require patches).
    • Check for forks or alternatives like symfony/ux-rpc.
  2. Annotation Processing

    • Ensure doctrine/annotations is installed and configured in composer.json:
      "require": {
          "doctrine/annotations": "^1.0"
      }
      
    • Clear cache after adding new @RpcMethod annotations:
      php bin/console cache:clear
      
  3. CORS Issues The bundle does not include CORS middleware by default. Add it manually:

    # config/packages/nelmio_cors.yaml
    nelmio_cors:
        defaults:
            allow_origin: ["*"]
            allow_methods: ["POST"]
            allow_headers: ["Content-Type"]
            expose_headers: ["*"]
    
  4. Parameter Validation

    • The bundle lacks built-in validation. Use Symfony’s Validator component:
      use Symfony\Component\Validator\Constraints as Assert;
      
      /**
       * @RpcMethod("user.update")
       * @Assert\Type("App\Dto\UserDto")
       */
      public function updateUser(UserDto $user)
      
  5. Circular Dependencies Avoid circular references in RPC services (e.g., ServiceA calling ServiceB which calls ServiceA). Use dependency injection carefully.


Debugging Tips

  1. Enable Debug Mode Set APP_DEBUG=1 in .env to see detailed RPC call logs in Symfony’s profiler.

  2. Check Event Dispatching Use RpcEvent listeners to inspect calls:

    public function onRpcCall(RpcEvent $event)
    {
        dump($event->getMethod(), $event->getParams());
    }
    
  3. Test with curl Validate RPC calls manually:

    curl -X POST http://localhost/api/rpc \
      -H "Content-Type: application/json" \
      -d '{"method":"add","params":[1,2]}'
    
  4. Common Errors

    • 404 Not Found: Verify the endpoint path and method name in annotations.
    • 500 Server Error: Check for unhandled exceptions in RPC methods (enable APP_DEBUG).
    • JSON Parse Error: Ensure the request payload is valid JSON.

Extension Points

  1. Custom Serialization Override default JSON serialization by implementing RpcSerializerInterface:

    class CustomSerializer implements RpcSerializerInterface
    {
        public function serialize($data): string
        {
            return json_encode($data, JSON_PRETTY_PRINT);
        }
    
        public function deserialize(string $data): array
        {
            return json_decode($data, true);
        }
    }
    

    Register it in services.yaml:

    services:
        App\Serializer\CustomSerializer:
            tags: ['rpc.serializer']
    
  2. Middleware Support Add pre/post-processing middleware:

    devim_rpc_server:
        middlewares:
            - App\Middleware\RpcLoggingMiddleware
    
  3. Dynamic Endpoints Register RPC methods dynamically via RpcMethodRegistry:

    $registry->addMethod('dynamic.method', [$this, 'dynamicAction']);
    
  4. Batch Processing Extend the bundle to support batch RPC calls (e.g., {"methods": [{"name": "add", "params": [...]}, ...]}).

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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