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

Command Laravel Package

guzzlehttp/command

Build higher-level web service clients on top of Guzzle by modeling operations as Commands and responses as Results. Includes a generic ServiceClient plus command middleware to map commands to PSR-7 requests and responses to structured results.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Abstraction Layer: The package provides a clean abstraction over raw HTTP requests via Commands and Results, making it ideal for Laravel applications where API integrations are common (e.g., third-party services, microservices, or legacy APIs). It aligns well with Laravel’s service container and dependency injection patterns.
  • Middleware Support: The dual middleware system (HTTP and command-level) allows granular control over request/response transformations, logging, retries, and authentication—critical for Laravel’s modular architecture.
  • PSR Compliance: Adherence to PSR-7 (HTTP messages) and PSR-15 (HTTP middleware) ensures compatibility with Laravel’s ecosystem (e.g., illuminate/http uses PSR-7 under the hood).

Integration Feasibility

  • Laravel Service Providers: The ServiceClient can be instantiated in a Laravel Service Provider, injected via the container, and configured with Guzzle’s HTTP client (already used in Laravel for HTTP requests).
  • Command Bus Pattern: The package’s command/result pattern maps naturally to Laravel’s console commands, queued jobs, or API controllers, reducing boilerplate for API clients.
  • Existing Laravel Packages: Compatible with packages like guzzlehttp/guzzle (already in Laravel’s vendor), spatie/laravel-activitylog (for auditing), or spatie/laravel-queue-priority (for async commands).

Technical Risk

  • Learning Curve: Developers unfamiliar with Guzzle’s middleware or PSR standards may require training, though Laravel’s existing HTTP client usage mitigates this.
  • Async Complexity: While executeAsync() and executeAllAsync() are powerful, Laravel’s queue system (e.g., Illuminate\Queue) might overlap, requiring careful design to avoid redundancy.
  • Error Handling: Laravel’s exception handling (e.g., App\Exceptions\Handler) must be extended to map CommandException to Laravel’s HttpResponseException or custom exceptions.
  • Performance Overhead: Middleware layers add minimal overhead, but concurrent requests (executeAll) could strain Laravel’s event loop if not throttled (e.g., via concurrency option).

Key Questions

  1. Use Case Alignment:
    • Is this for internal microservices, third-party APIs, or legacy SOAP/REST wrappers? The package excels at structured API clients.
    • Will commands be synchronous (e.g., in controllers) or asynchronous (e.g., in queues)? Async requires Laravel queue integration.
  2. Middleware Strategy:
    • Should command middleware handle authentication, rate limiting, or logging? Laravel’s middleware groups (e.g., kernel.php) can complement this.
    • Will HTTP middleware (e.g., retries, timeouts) duplicate Laravel’s HttpClient configurations?
  3. Error Recovery:
    • How should failed commands be retried? Laravel’s Illuminate\Support\Retry or queue retries could integrate.
    • Should CommandException be translated to Laravel’s ProblemException or custom DTOs?
  4. Testing:
    • How will mocking CommandInterface/ResultInterface work in Laravel’s testing tools (e.g., Mockery, Pest)?
  5. Scaling:
    • Will high concurrency (executeAll) require Laravel’s queue workers or a separate process (e.g., reactphp)?

Integration Approach

Stack Fit

  • Laravel HTTP Client: Replace or extend Laravel’s built-in Http facade with ServiceClient for API-heavy applications. The underlying GuzzleHttp\Client is already used by Laravel’s Http client.
  • Service Container: Register ServiceClient as a singleton or context-bound instance in AppServiceProvider:
    $this->app->singleton('api.client', function ($app) {
        return new ServiceClient(
            $app->make(GuzzleHttp\Client::class),
            // Command-to-Request transformer...
            // Response-to-Result transformer...
        );
    });
    
  • Async Integration: Use Laravel’s queue system to dispatch async commands:
    $client->executeAsync($command)->then(function ($result) {
        dispatch(new ProcessResultJob($result));
    });
    
  • Middleware: Leverage Laravel’s middleware pipeline for HTTP-level concerns (e.g., auth) and use ServiceClient middleware for command-level logic (e.g., input validation).

Migration Path

  1. Phase 1: Pilot Integration
    • Start with a single API client (e.g., Stripe, GitHub) using ServiceClient.
    • Replace ad-hoc Http::post() calls with structured commands.
    • Example:
      // Before
      $response = Http::post('api/users', ['name' => 'John']);
      
      // After
      $result = $client->createUser(['name' => 'John']);
      
  2. Phase 2: Middleware Adoption
    • Migrate HTTP middleware (e.g., retries) from Laravel’s Http client to Guzzle’s HandlerStack.
    • Add command middleware for cross-cutting concerns (e.g., logging, metrics).
  3. Phase 3: Async Expansion
    • Replace synchronous queue jobs with executeAsync for long-running operations.
    • Use Laravel’s dispatchSync for testing async flows.
  4. Phase 4: Full Replacement
    • Deprecate custom API client wrappers in favor of ServiceClient.
    • Standardize error handling across all API calls.

Compatibility

  • Laravel Versions: Supports PHP 8.0+ (Laravel 9+) and Guzzle 7.x, which aligns with Laravel’s current stack.
  • Guzzle Extensions: Works with Laravel’s guzzlehttp/guzzle and guzzlehttp/promises (used by Laravel’s queue system).
  • PSR-7: Laravel’s illuminate/http uses PSR-7 under the hood, so no conflicts.
  • Database/ORM: No direct integration, but commands can trigger Eloquent models (e.g., User::create($result->toArray())).

Sequencing

  1. Prerequisites:
    • Ensure guzzlehttp/guzzle and guzzlehttp/promises are pinned to compatible versions (e.g., ^7.10).
    • Add GuzzleHttp\Command\* to composer.json:
      composer require guzzlehttp/command
      
  2. Initial Setup:
    • Create a base ServiceClient in a service provider.
    • Define command/result transformers for the first API.
  3. Incremental Rollout:
    • Start with read-only commands (e.g., getUser).
    • Gradually add write operations (e.g., createOrder).
  4. Testing:
    • Write feature tests for command execution (e.g., assertEquals($result['id'], 123)).
    • Mock CommandInterface in unit tests:
      $mockCommand = Mockery::mock(CommandInterface::class);
      $mockCommand->shouldReceive('getName')->andReturn('createUser');
      
  5. Monitoring:
    • Instrument middleware to log command execution times and failures.
    • Use Laravel’s debugbar to inspect request/response cycles.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Commands centralize API logic, reducing duplicate HTTP code.
    • Consistent Error Handling: Middleware standardizes retries, timeouts, and logging.
    • Type Safety: PHP 8.0+ return types (CommandInterface, ResultInterface) improve IDE support.
  • Cons:
    • Middleware Complexity: Adding/removing middleware requires testing all command paths.
    • Dependency Updates: Guzzle updates may require ServiceClient adjustments (e.g., PSR-7 changes).

Support

  • Debugging:
    • Use Laravel’s tap() or dd() to inspect commands/results:
      $result = $client->createUser(['name' => 'John'])->tap(function ($result) {
          Log::debug('Command result:', $result->toArray());
      });
      
    • Guzzle’s built-in logging middleware can be added to the HandlerStack.
  • Common Issues:
    • Reserved Keys: Accidental use of @http in user input (mitigate via input validation).
    • Async Deadlocks: Ensure async commands don’t block Laravel’s event loop (use queues for heavy workloads).
    • CORS/CSRF: If used in Blade templates, ensure CSRF tokens are handled via Laravel’s csrf_token().

Scaling

  • Concurrency:
    • Limit executeAll concurrency to avoid overwhelming the API or Laravel’s workers.
    • Example: Set concurrency: 5 for external APIs with rate limits.
  • Performance:
    • Caching: Cache command results (e.g., Cache::remember) for idempotent operations.
    • Batch Processing: Use executeAll for bulk operations (e.g., syncing users).
  • Horizontal Scaling:
    • Stateless `
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