Weave 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

Micro Service Common Laravel Package

bricre/micro-service-common

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require bricre/micro-service-common
    

    Publish the package configuration (if applicable):

    php artisan vendor:publish --provider="Bricre\MicroServiceCommon\MicroServiceCommonServiceProvider"
    
  2. First Use Case: API Client If the package includes HTTP client utilities (common in micro-service toolkits), initialize a client in a service:

    use Bricre\MicroServiceCommon\Clients\ApiClient;
    
    $client = new ApiClient(config('services.my_microservice.url'));
    $response = $client->get('/endpoint');
    
  3. First Use Case: Logging If logging utilities are included, configure in config/logging.php:

    'channels' => [
        'microservice' => [
            'driver' => 'single',
            'path' => storage_path('logs/microservice.log'),
            'level' => 'debug',
        ],
    ],
    

    Use in a controller:

    use Bricre\MicroServiceCommon\Support\Logger;
    
    Logger::debug('User action', ['user_id' => 123]);
    
  4. First Use Case: Request Validation If validation helpers exist, extend a request:

    use Bricre\MicroServiceCommon\Http\Requests\MicroServiceFormRequest;
    
    class CreateUserRequest extends MicroServiceFormRequest
    {
        public function rules()
        {
            return [
                'name' => 'required|string|max:255',
                'email' => 'required|email',
            ];
        }
    }
    

Implementation Patterns

Common Workflows

  1. Service-to-Service Communication

    • Pattern: Use the ApiClient for internal service calls.
    • Workflow:
      // In a service class
      public function fetchUserData($userId)
      {
          $client = app(ApiClient::class);
          $response = $client->get("/users/{$userId}");
          return json_decode($response->getBody(), true);
      }
      
    • Tip: Cache responses for idempotent operations using Laravel's cache.
  2. Request/Response Transformation

    • Pattern: Use middleware or decorators to standardize API responses.
    • Example:
      // app/Http/Middleware/TransformResponse.php
      public function handle($request, Closure $next)
      {
          $response = $next($request);
          return $response->json([
              'success' => true,
              'data' => $response->getData(),
              'timestamp' => now()->toIso8601String(),
          ]);
      }
      
  3. Event-Driven Architecture

    • Pattern: Dispatch events for cross-service communication.
    • Example:
      use Bricre\MicroServiceCommon\Events\UserCreated;
      
      event(new UserCreated($user));
      
    • Listener:
      public function handle(UserCreated $event)
      {
          // Notify other services via API or queue
      }
      
  4. Configuration Management

    • Pattern: Centralize service URLs and tokens in config/services.php.
    • Example:
      'microservices' => [
          'auth' => [
              'url' => env('AUTH_SERVICE_URL'),
              'token' => env('AUTH_SERVICE_TOKEN'),
          ],
          'inventory' => [
              'url' => env('INVENTORY_SERVICE_URL'),
          ],
      ],
      

Integration Tips

  • Laravel Service Container: Bind interfaces to implementations in AppServiceProvider:

    $this->app->bind(
        Bricre\MicroServiceCommon\Contracts\LoggerInterface::class,
        Bricre\MicroServiceCommon\Support\Logger::class
    );
    
  • Queue Jobs: Use the package's queue helpers for async operations:

    use Bricre\MicroServiceCommon\Jobs\ProcessOrder;
    
    ProcessOrder::dispatch($order)->onQueue('microservices');
    
  • Testing: Mock the ApiClient in unit tests:

    $mock = Mockery::mock(ApiClient::class);
    $mock->shouldReceive('get')->once()->andReturn(new Response(200, [], '{}'));
    $this->app->instance(ApiClient::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • Issue: Package configs may not merge correctly with existing Laravel configs.
    • Fix: Use config(['key' => 'value']) to override specific settings after publishing.
  2. HTTP Client Timeouts

    • Issue: Default timeouts may be too short for slow services.
    • Fix: Configure in config/micro-service-common.php:
      'http' => [
          'timeout' => 30, // seconds
          'connect_timeout' => 5,
      ],
      
  3. Circular Dependencies

    • Issue: Services A and B calling each other directly can cause deadlocks.
    • Fix: Use event-driven communication or a centralized API gateway.
  4. Logging Overhead

    • Issue: Excessive logging in high-traffic services.
    • Fix: Disable debug logs in production:
      Logger::setLevel(env('APP_ENV') === 'production' ? 'info' : 'debug');
      
  5. Rate Limiting

    • Issue: Unhandled rate limits from dependent services.
    • Fix: Implement retry logic with exponential backoff:
      use Bricre\MicroServiceCommon\Exceptions\RateLimitExceeded;
      
      try {
          $response = $client->get('/endpoint');
      } catch (RateLimitExceeded $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      

Debugging Tips

  1. Enable Verbose Logging

    php artisan config:set micro-service-common.log.level=debug
    
  2. Inspect HTTP Requests Use Laravel's built-in HTTP client logging:

    $client->withOptions([
        'debug' => fopen(storage_path('logs/http_client.log'), 'w'),
    ]);
    
  3. Check for Deprecated Methods Run:

    php artisan vendor:analyze --provider="Bricre\MicroServiceCommon\MicroServiceCommonServiceProvider"
    

Extension Points

  1. Custom Middleware Extend the ApiClient with middleware:

    $client->withMiddleware([
        new AddAuthHeader(),
        new LogRequest(),
    ]);
    
  2. Event Listeners Subscribe to package events in EventServiceProvider:

    protected $listen = [
        'Bricre\MicroServiceCommon\Events\ServiceDown' => [
            'App\Listeners\NotifyDevOps',
        ],
    ];
    
  3. Custom Validators Extend the base MicroServiceFormRequest:

    class CustomRequest extends MicroServiceFormRequest
    {
        public function authorize()
        {
            return auth()->check() && auth()->user()->isAdmin();
        }
    }
    
  4. Service Discovery Dynamically resolve service URLs via DNS or consul:

    $serviceUrl = app('service.discovery')->get('auth-service');
    
  5. Testing Utilities Use the package's test helpers:

    use Bricre\MicroServiceCommon\Testing\TestApiClient;
    
    public function testServiceCall()
    {
        $client = new TestApiClient();
        $client->shouldReceive('get')->andReturn(['data' => 'test']);
    }
    
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.
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core