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

Promises Laravel Package

guzzlehttp/promises

Promises/A+ implementation for PHP with iterative, stack-safe chaining. Provides synchronous wait(), cancellation, interop with any thenable, and coroutine-style async/await via Coroutine::of(). Includes Promise, FulfilledPromise, and RejectedPromise.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Asynchronous Workflows: The package excels in modeling asynchronous operations (e.g., HTTP requests, database queries, or external API calls) where chaining and error handling are critical. It aligns well with Laravel’s event-driven architecture, particularly for background jobs, queues, or real-time processing.
  • Promise-Based Patterns: The Promises/A+ implementation enables clean chaining of async operations, reducing callback hell and improving readability. This is especially useful in Laravel for tasks like:
    • Parallel HTTP requests (e.g., fetching data from multiple APIs).
    • Sequential or conditional workflows (e.g., processing queue jobs with dependencies).
    • Retry mechanisms with exponential backoff.
  • Interoperability: Works with other promise libraries (e.g., ReactPHP) and Laravel’s native async tools (e.g., Illuminate\Support\Facades\Http with async calls), though integration requires explicit wrapping.

Integration Feasibility

  • Laravel Ecosystem Synergy:
    • Queues/Jobs: Can replace nested then() callbacks in Illuminate\Bus\Queueable jobs with promise chains for complex workflows.
    • HTTP Client: Complements GuzzleHttp (Laravel’s default HTTP client) for async request handling, though Laravel’s Http::async() already uses promises under the hood.
    • Events: Useful for async event listeners where operations must complete before triggering follow-up actions.
  • Existing Laravel Patterns:
    • Service Containers: Promises can be injected as dependencies for async operations (e.g., resolve() a promise in a service method).
    • Middleware: Async middleware for pre/post-processing requests (e.g., caching, rate limiting).
  • Limitations:
    • No native Laravel integration (e.g., no Promise::resolve() helper like response() or redirect()).
    • Requires manual handling of event loops for async contexts (e.g., ReactPHP, Swoole).

Technical Risk

  • Event Loop Dependency:
    • Risk: Without an event loop (e.g., ReactPHP, Swoole), promises won’t resolve automatically. Laravel’s synchronous runtime (e.g., CLI, HTTP requests) may block indefinitely if promises aren’t unwrapped via wait().
    • Mitigation: Use wait() for synchronous contexts or integrate with Laravel’s async tools (e.g., Http::async() + then()).
  • Error Handling Complexity:
    • Risk: Nested then()/catch() chains can become hard to debug. Laravel’s exception handling (e.g., try/catch) may not seamlessly translate to promise rejections.
    • Mitigation: Use otherwise() for rejection handling and wrap promises in Laravel’s try/catch where needed.
  • Performance Overhead:
    • Risk: Iterative resolution (to avoid stack overflow) adds minor overhead. For high-throughput systems (e.g., 10K+ concurrent promises), monitor memory usage.
    • Mitigation: Benchmark under load; consider batching promises where possible.
  • Version Compatibility:
    • Risk: Laravel 10+ uses PHP 8.1+, but guzzlehttp/promises v2 requires PHP ≥7.2.5. Ensure alignment with Laravel’s PHP version constraints.
    • Mitigation: Use v2.x for new projects; v1.x for legacy PHP 5.5–8.2 systems (security fixes only).

Key Questions

  1. Async Context:
    • Will this package replace Laravel’s existing async tools (e.g., Http::async(), queues), or augment them? If the latter, how will they interoperate?
    • Example: Can GuzzleHttp\Promise\Coroutine replace Laravel’s Bus::dispatchSync() for async jobs?
  2. Event Loop Strategy:
    • How will promises be resolved in Laravel’s synchronous runtime (e.g., HTTP routes)? Will wait() be used, or will an event loop (e.g., ReactPHP) be introduced?
  3. Error Recovery:
    • How will promise rejections be translated into Laravel exceptions (e.g., Handler classes, middleware)? Will custom RejectionException handlers be needed?
  4. Testing:
    • How will promise-based workflows be unit/integration tested? Laravel’s testing tools (e.g., Mockery, Http::fake()) may need extensions for async assertions.
  5. Scaling:
    • What’s the expected scale (e.g., concurrent promises)? Will Laravel’s queue workers or a separate event loop (e.g., Swoole) handle resolution?

Integration Approach

Stack Fit

  • Laravel Core:
    • HTTP Client: Replace or extend Http::async() with GuzzleHttp\Promise for custom async logic (e.g., retry policies, parallel requests).
    • Queues: Use promises to chain dependent jobs (e.g., JobA resolves to JobB).
    • Events: Async event listeners where promises trigger follow-up actions.
  • Third-Party Libraries:
    • ReactPHP/Swoole: Integrate with Laravel’s async servers (e.g., laravel-react) for event loop support.
    • Database: Use with Eloquent events or query builders for async database operations (e.g., bulk inserts).
  • Legacy Code:
    • Callback Hell: Refactor nested callbacks (e.g., in custom HTTP clients or services) into promise chains.

Migration Path

  1. Incremental Adoption:
    • Start with non-critical async operations (e.g., logging, analytics) to test promise integration.
    • Example: Replace a callback-based retry mechanism with a promise chain.
  2. Wrapper Classes:
    • Create Laravel-specific facades or helpers to abstract promise usage (e.g., Promise::fromQueueJob()).
    • Example:
      class PromiseFacade {
          public static function resolveFromJob(QueueableInterface $job) {
              return new Promise(function () use ($job) {
                  $job->handle();
              });
          }
      }
      
  3. Event Loop Integration:
    • For async contexts (e.g., Laravel Octane, ReactPHP), integrate the Guzzle task queue:
      // In a ReactPHP event loop
      $loop = React\EventLoop\Factory::create();
      $loop->addPeriodicTimer(0.01, [GuzzleHttp\Promise\Utils::queue(), 'run']);
      
  4. Testing First:
    • Write promise-aware tests using wait() for synchronous assertions or mock event loops for async tests.

Compatibility

  • Laravel 10+:
    • Fully compatible with PHP 8.1+ and Guzzle v7+. Leverage GuzzleHttp\Promise\Coroutine for async/await-style code.
  • Laravel <10:
    • Use v1.x for PHP 5.5–8.2 support, but prioritize upgrading to v2.x for new features.
  • Guzzle HTTP Client:
    • Existing GuzzleHttp\Client instances can use GuzzleHttp\Promise via requestAsync():
      $client = new Client();
      $promise = $client->requestAsync('GET', 'https://api.example.com');
      $promise->then(function (ResponseInterface $response) {
          // Handle response
      });
      
  • Queues:
    • Custom queue workers can resolve promises before dispatching follow-up jobs:
      public function handle() {
          $promise = new Promise(function () {
              // Async operation (e.g., external API call)
          });
          $promise->then(function () {
              dispatch(new FollowUpJob());
          });
      }
      

Sequencing

  1. Phase 1: Proof of Concept
    • Implement a single promise-based workflow (e.g., async image processing).
    • Validate error handling and performance.
  2. Phase 2: Core Integration
    • Add promise support to Laravel’s HTTP client or queue system.
    • Example: Extend Illuminate\Http\Client\PendingRequest with then().
  3. Phase 3: Event Loop
    • Integrate with ReactPHP/Swoole for async Laravel applications (e.g., Octane).
  4. Phase 4: Documentation
    • Publish guides for:
      • Promise chaining in jobs.
      • Async HTTP requests.
      • Event loop setup.

Operational Impact

Maintenance

  • Dependency Management:
    • Monitor guzzlehttp/promises for security updates (MIT license, active maintenance).
    • Align version upgrades with Laravel’s Guzzle dependencies (e.g., Laravel 10 uses Guzzle v7+).
  • Debugging:
    • Promises add complexity to stack traces. Use getState() and custom logging to track promise lifecycles:
      $promise->then(
          fn($value) => logger()->debug('Fulfilled', ['value' => $value]),
          fn($reason) => logger()->error('Rejected', ['reason' => $reason])
      );
      
  • Testing:
    • Write promise-aware tests:
      • Synchronous: Use wait() for assertions.
      • Asynchronous: Mock event loops or use React\Promise\Timer for timeouts.

Support

  • Developer Onboarding:
    • Promises require understanding
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata