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

Promise Laravel Package

php-standard-library/promise

Lightweight Promise implementation for PHP with a simple, standards-inspired API. Create, resolve, reject, and chain async-style operations, handle errors, and compose results with familiar then/catch patterns—ideal for libraries that need non-blocking workflows.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Synergy: Aligns with Laravel’s async patterns (queues, jobs) while introducing a structured, composable abstraction for deferred computations. Ideal for scenarios requiring orchestration of async operations (e.g., chaining API calls, parallelizing queue jobs) without adopting a full event loop.
  • Hybrid Sync/Async: Complements Laravel’s synchronous-by-default architecture by enabling explicit async workflows in bounded contexts (e.g., service layers, background jobs). Avoids the complexity of ReactPHP/Amp while offering better maintainability than raw callbacks.
  • Library Portability: Designed for reusability across projects or teams, making it suitable for internal SDKs, API clients, or shared infrastructure (e.g., a DataFetcher service layer).
  • Future-Proofing: Provides a foundation for event-driven architectures by standardizing async primitives. Can later integrate with Laravel’s async features (e.g., Laravel\Promises) or external event loops.

Integration Feasibility

  • Laravel Ecosystem Compatibility:
    • Queues/Jobs: Promises can wrap dispatch() calls or Bus::dispatch() for chained execution (e.g., Promise::all([job1(), job2()])).
    • HTTP Clients: Works seamlessly with Guzzle/PestHTTP via adapters (e.g., GuzzlePromise::send()).
    • Events: Enables async event listeners (e.g., event1.then(() => event2)).
    • Database: Can abstract async queries (e.g., Promise::resolve(DB::select(...))).
  • Dependency Minimalism: No heavy frameworks; integrates cleanly with Laravel’s existing tooling (e.g., no conflict with Symfony components).
  • PHP Version: Assumes PHP 8.0+ (aligned with Laravel’s LTS support), with no breaking changes in recent releases.

Technical Risk

  • No Built-in Concurrency: Promises do not parallelize work—they only structure async execution. Requires underlying async mechanisms (e.g., Queues, Swoole) for true concurrency.
  • Error Handling Complexity: PHP’s lack of native async/await means catch blocks must use callbacks, risking inconsistent error surfaces if not disciplined (e.g., unhandled rejections).
  • Debugging Challenges: Async flows are harder to trace in production. Requires tooling (e.g., Telescope, Xdebug async support) or custom logging.
  • Performance Overhead: Micro-optimizations may be needed for high-throughput scenarios (e.g., batching Promise::all() calls).
  • Adoption Friction: Teams accustomed to callbacks or Queues may resist learning Promise patterns (e.g., .then() chaining, combinators).

Key Questions

  1. Execution Strategy:
    • How will Promises be resolved? (e.g., via Laravel Queues, custom event loop, or synchronous callbacks?)
    • Will this require a hybrid architecture (e.g., Promises for orchestration + Queues for execution)?
  2. Error Resilience:
    • How will global Promise rejections be handled? (e.g., logging, Sentry integration, fallback mechanisms?)
    • Are there circuit breakers for failed async operations?
  3. Scope and Boundaries:
    • Will Promises be used in core application logic (risky for monoliths) or bounded contexts (e.g., API clients, background jobs)?
    • How will mixed sync/async code be managed to avoid race conditions?
  4. Tooling and Observability:
    • Are there plans to integrate with Laravel Telescope or Sentry for Promise debugging?
    • How will async code paths be tested? (e.g., mocking Promises in unit tests)
  5. Alternatives:
    • Could Laravel’s built-in Illuminate\Support\Facades\Bus or Illuminate\Queue suffice, or is a Promise layer necessary for composability?
    • Is there a need for native PHP fibers (PHP 8.1+) or a full event loop (e.g., ReactPHP) instead?
  6. Performance:
    • What are the throughput requirements? (e.g., 1000s of Promises/sec may need batching or a different approach.)
    • How will memory leaks (e.g., unresolved Promises) be prevented?

Integration Approach

Stack Fit

  • Primary Use Cases in Laravel:
    • API Integrations: Chain or parallelize HTTP requests (e.g., Promise::all([fetchUser(), fetchOrders()])).
    • Queue Workers: Orchestrate dependent jobs (e.g., Promise::then() after dispatch()).
    • Event-Driven Logic: Compose async event handlers (e.g., event1.then(() => processEvent2())).
    • Database Operations: Abstract async queries (e.g., Promise::resolve(DB::transaction(...))).
    • Background Tasks: Replace nested callbacks in Artisan commands or scheduled jobs.
  • Laravel-Specific Synergies:
    • Service Providers: Register a Promise facade for global access (e.g., app('promise')).
    • Macros/Helpers: Extend Laravel’s Bus or Queue to return Promises natively (e.g., Bus::dispatchAsPromise($job)).
    • Testing: Use Mockery or Laravel\Promises test helpers to stub Promise resolutions.
    • Monitoring: Integrate with Telescope for Promise state logging (e.g., resolved/rejected timestamps).

Migration Path

  1. Pilot Phase (1–2 Weeks):

    • Target: A single bounded context (e.g., a feature with nested callbacks).
    • Actions:
      • Replace callback pyramids with Promise chains (e.g., Guzzle requests → Promise::all() → aggregate data).
      • Add basic error handling (e.g., .catch() blocks).
      • Document the pattern for the team.
    • Example:
      // Before (Callbacks)
      $client->request('GET', '/user')->then(function ($user) {
          $client->request('GET', '/orders')->then(function ($orders) {
              return $user + $orders;
          });
      });
      
      // After (Promises)
      Promise::all([
          $client->request('GET', '/user'),
          $client->request('GET', '/orders')
      ])->then(function ($results) {
          return array_merge($results[0], $results[1]);
      });
      
  2. Core Integration (2–4 Weeks):

    • Target: Extend to queue workers, event listeners, and service layers.
    • Actions:
      • Create Promise-aware facades (e.g., Promise::dispatch($job) to wrap Bus::dispatch()).
      • Build combinator utilities (e.g., Promise::race(), Promise::any(), Promise::allSettled()).
      • Integrate with Laravel’s HTTP clients (e.g., GuzzlePromise adapter).
    • Example:
      // Queue Worker with Promises
      class ProcessOrder implements ShouldQueue {
          public function handle() {
              return Promise::all([
                  $this->fetchUserData(),
                  $this->validatePayment(),
              ])->then(function ($results) {
                  // Process results
              })->catch(function ($e) {
                  Log::error("Order processing failed: " . $e->getMessage());
              });
          }
      }
      
  3. Tooling and Observability (4+ Weeks):

    • Target: Production readiness.
    • Actions:
      • Integrate with Telescope to log Promise states/rejections.
      • Add Sentry integration for error tracking.
      • Build custom monitoring (e.g., track Promise resolution times).
      • Document failure modes and mitigation strategies.

Compatibility

  • Laravel Ecosystem:
    • Queues: Promises can wrap dispatch() calls but do not replace the queue system. Useful for orchestrating dependent jobs.
    • HTTP Clients: Works with Guzzle/PestHTTP via custom adapters (e.g., GuzzlePromise::send($request)).
    • Events: Can bridge Event::dispatch() with Promises for async listeners.
    • Database: Can abstract async queries but does not replace Eloquent’s sync methods.
  • Third-Party Packages:
    • Spatie Async: Could complement this for event-loop integration (if needed later).
    • Amp/PReact: Avoid unless migrating to full async PHP (this library is lighter and Laravel-focused).
    • Laravel Promises: If using illuminate/promises, evaluate whether this library adds value (e.g., for cross-framework compatibility).

Sequencing

Phase Duration Focus Areas Deliverables
Pilot 1–2 weeks Replace callbacks in a single
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui