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

Microservice Framework Bundle Laravel Package

cmobi/microservice-framework-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require cmobi/microservice-framework-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        ContaMobi\MicroserviceFrameworkBundle\ContaMobiMicroserviceFrameworkBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console cmobi:microservice:init
    

    Edit config/packages/cmobi_microservice_framework.yaml to define:

    • Service discovery (e.g., Consul, Eureka, or static endpoints).
    • API gateway routing rules.
    • Service-to-service communication protocols (HTTP/gRPC).
  3. First Use Case: Service Registration Annotate a Symfony service as a microservice:

    use ContaMobi\MicroserviceFrameworkBundle\Annotation\Microservice;
    
    #[Microservice(name: 'user-service', port: 8000)]
    class UserService {}
    

    Register the service with the framework:

    php bin/console cmobi:microservice:register
    
  4. Testing Locally Use the built-in ProxyClient to test inter-service calls:

    $client = $container->get('cmobi.microservice.proxy_client');
    $response = $client->call('user-service', 'GET', '/api/users/1');
    

Implementation Patterns

Service Discovery & Communication

  1. Dynamic Routing Configure API gateway rules in yaml to route requests to specific services:

    cmobi_microservice_framework:
        api_gateway:
            routes:
                '/users': 'user-service'
                '/orders': 'order-service'
    

    Use the GatewayClient to forward requests:

    $gateway = $container->get('cmobi.microservice.gateway_client');
    $response = $gateway->forward('/users', 'GET');
    
  2. Inter-Service Calls Inject the ProxyClient into controllers/services:

    public function __construct(private ProxyClient $proxyClient) {}
    
    public function fetchUserData(int $id) {
        return $this->proxyClient->call('user-service', 'GET', "/users/{$id}");
    }
    
  3. Event-Driven Workflows Publish/subscribe to events across services:

    // In Service A:
    $eventDispatcher = $container->get('event_dispatcher');
    $eventDispatcher->dispatch(new UserCreatedEvent($user));
    
    // In Service B (listening via Symfony Messenger or custom subscriber):
    #[Asynchronous]
    public function handleUserCreated(UserCreatedEvent $event) {
        // Process event...
    }
    

Workflows

  1. Circuit Breaker Pattern Enable resilience with the CircuitBreaker decorator:

    $client = new CircuitBreaker($proxyClient, 3, 1000); // 3 failures, 1s timeout
    $response = $client->call('failing-service', 'GET', '/health');
    
  2. Service Health Checks Implement a health check endpoint in each service:

    #[Route('/health', name: 'health_check', methods: ['GET'])]
    public function healthCheck(): JsonResponse {
        return new JsonResponse(['status' => 'healthy']);
    }
    

    Register the endpoint in the bundle config:

    cmobi_microservice_framework:
        health_checks:
            - 'user-service:8000/health'
            - 'order-service:8001/health'
    
  3. Configuration Management Use environment-specific configs (e.g., config/packages/dev/cmobi_microservice_framework.yaml) to switch between:

    • Local service discovery (static endpoints).
    • Cloud-based discovery (Consul/Eureka).

Gotchas and Tips

Pitfalls

  1. Service Discovery Lag

    • Issue: Services may not be immediately discoverable after registration.
    • Fix: Use php bin/console cmobi:microservice:register --force or implement a retry mechanism in ProxyClient.
  2. Circular Dependencies

    • Issue: Services A and B calling each other can cause deadlocks.
    • Fix: Use async event dispatching or implement a priority-based routing system.
  3. Configuration Overrides

    • Issue: Local overrides may conflict with deployed configs.
    • Fix: Use environment variables to dynamically set critical values (e.g., MICROSERVICE_DISCOVERY_URL).
  4. Annotation Caching

    • Issue: Changes to @Microservice annotations require cache clearing.
    • Fix: Run php bin/console cache:clear after modifying annotated classes.

Debugging Tips

  1. Enable Verbose Logging Configure monolog in config/packages/monolog.yaml:

    handlers:
        cmobi_microservice:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.cmobi.log"
            level: debug
    
  2. Inspect Service Registry Dump the registered services:

    php bin/console debug:container | grep cmobi.microservice
    
  3. Mock External Services Use the MockProxyClient for testing:

    $mockClient = new MockProxyClient();
    $mockClient->shouldReceive('call')
        ->with('user-service', 'GET', '/users/1')
        ->andReturn(['id' => 1, 'name' => 'Test User']);
    

Extension Points

  1. Custom Discovery Providers Extend DiscoveryProviderInterface to support new backends (e.g., Kubernetes):

    class KubernetesDiscoveryProvider implements DiscoveryProviderInterface {
        public function getServices(): array {
            // Fetch from Kubernetes API
        }
    }
    

    Register in config:

    cmobi_microservice_framework:
        discovery_provider: ContaMobi\MicroserviceFrameworkBundle\Discovery\KubernetesDiscoveryProvider
    
  2. Protocol Plugins Add support for gRPC or WebSockets by implementing ProtocolHandlerInterface:

    class GrpcProtocolHandler implements ProtocolHandlerInterface {
        public function handle(string $service, string $method, array $data): mixed {
            // gRPC logic
        }
    }
    
  3. Custom Metadata Extend the @Microservice annotation to include additional metadata (e.g., priority, retries):

    #[Microservice(
        name: 'user-service',
        port: 8000,
        retries: 2,
        priority: 1
    )]
    

Performance Quirks

  • Avoid Blocking Calls: Use async clients (e.g., ReactPHP) for long-running operations.
  • Bulkhead Resources: Limit concurrent calls to a service to prevent cascading failures:
    cmobi_microservice_framework:
        bulkheads:
            'user-service': 10  # Max 10 concurrent calls
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle