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

internal/promise

Lightweight Promises/A implementation for PHP (fork of reactphp/promise). PHP 8.1+ compatible with strict types and improved type annotations. Drop-in replacement for react/promise v2/v3 with reusable rejection handling and safer defaults.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven & Async Workflows: Perfect fit for Laravel’s queue workers, HTTP clients, and real-time features (e.g., WebSockets, database listeners). Aligns with Laravel’s growing async ecosystem (e.g., spatie/async).
  • Promise/A Compatibility: Enables composable async chains (e.g., Promise.all() for parallel API calls) without callback hell, reducing cognitive complexity.
  • Laravel Integration Points:
    • Queues: Replace queue:work callbacks with Deferred promises for chained async tasks.
    • HTTP Clients: Use Promise.race() to implement timeouts for external APIs.
    • Middleware: Leverage finally() for cleanup (e.g., logging, resource release).
  • Type Safety: PHP 8.4+ strict types (e.g., resolve(T $value)) catch bugs early, improving maintainability.

Integration Feasibility

  • Low Friction: Replaces reactphp/promise with 1:1 API parity (same methods: then(), catch(), all(), etc.).
  • Laravel Ecosystem Compatibility:
    • Works with Guzzle HTTP Client, Laravel Queues, and Laravel Echo (WebSockets).
    • Can integrate with Laravel’s Illuminate\Support\Facades via custom facades (e.g., Promise::resolve()).
  • Dependency Graph: Lightweight (~1MB) with no external PHP extensions required.

Technical Risk

Risk Area Mitigation Strategy
BC Breaks v3.x is stable; v2.x still supported for legacy. Test migration path (see below).
Error Handling Unhandled rejections logged by default (configurable via set_rejection_handler()).
Performance Benchmark against reactphp/promise; minimal overhead for I/O-bound tasks.
Fiber Support Avoids iterative handlers (better Fiber compatibility), but lacks native Fiber APIs.
Thread Safety Promises are single-threaded by design; safe for Laravel’s request lifecycle.

Key Questions

  1. Async Strategy:
    • Will this replace Laravel Queues entirely, or supplement them (e.g., for in-memory async)?
    • How will we handle long-running Promises (e.g., timeouts, cancellation)?
  2. Error Observability:
    • Should we extend set_rejection_handler() to integrate with Laravel’s logging (e.g., Log::error())?
  3. Testing:
    • How will we mock Promises in PHPUnit (e.g., for unit tests of async services)?
  4. Adoption Path:
    • Start with non-critical paths (e.g., API clients) before migrating queues.
    • Train devs on Promise patterns (e.g., all() vs. race()).

Integration Approach

Stack Fit

  • Laravel Core: Compatible with PHP 8.1+, Composer, and PSR-15 middleware.
  • Async Libraries:
    • Guzzle HTTP Client: Wrap Guzzle\Promise calls in internal/promise for unified error handling.
    • Laravel Queues: Use Deferred to chain jobs (e.g., dispatch()->then(fn() => dispatchNext())).
    • Laravel Echo: Handle WebSocket events as Promises (e.g., socket.on('message')->then(...)).
  • Database:
    • Eloquent: Replace DB::select() callbacks with Promise.resolve(DB::select(...)).
    • Query Builders: Chain async queries (e.g., User::where(...)->get()->then(...)).

Migration Path

Phase Action Tools/Examples
Evaluation Benchmark against reactphp/promise and Laravel’s native async tools (e.g., spatie/async). haute-couture/benchmark for performance; compare callback vs. Promise code.
Pilot Replace Guzzle callbacks with Promises in API services. Example: GuzzlePromise::promise()->then(...)Promise::resolve(Guzzle::request(...)).
Core Integration Add Promise facade to Laravel (config/app.php). Promise::all([$job1, $job2]) for parallel queue jobs.
Queue Migration Replace queue:work callbacks with Deferred chains. Deferred::promise()->then(fn() => dispatch('ProcessPayment')).
Error Handling Extend set_rejection_handler() to log to Laravel’s Log channel. Promise::set_rejection_handler(fn(Throwable $e) => Log::error($e));.

Compatibility

  • Backward Compatibility:
    • v3.x drops deprecated APIs (e.g., otherwise()), but provides BC aliases (e.g., catch() replaces otherwise()).
    • v2.x still supported for gradual migration.
  • Laravel-Specific:
    • Service Providers: Register Promise as a singleton in AppServiceProvider.
    • Facades: Create Promise facade for resolve(), reject(), etc.
    • Testing: Use Mockery to stub Promises in unit tests.

Sequencing

  1. Phase 1 (Week 1-2):
    • Add internal/promise to composer.json.
    • Replace Guzzle callbacks with Promises in API services.
    • Write integration tests for Promise chains.
  2. Phase 2 (Week 3-4):
    • Migrate queue jobs to use Deferred.
    • Add Promise facade and global rejection handler.
  3. Phase 3 (Week 5+):
    • Replace Eloquent callbacks with Promises.
    • Optimize parallel operations (e.g., Promise.all() for batch processing).

Operational Impact

Maintenance

  • Pros:
    • Production-Ready: Backed by ReactPHP’s battle-tested codebase.
    • Active Development: Regular updates (e.g., PHP 8.4 support, type safety).
    • Low Boilerplate: No need to maintain custom Promise logic.
  • Cons:
    • Dependency Risk: Relies on ReactPHP’s ecosystem (though internal/promise is standalone).
    • Learning Curve: Team must adopt Promise patterns (e.g., then/catch/finally).
  • Tooling:
    • PHPStan: Enforce type safety (already used by the package).
    • PestPHP: Test async workflows with expectPending().

Support

  • Debugging:
    • Unhandled Rejections: Logged by default (configurable via set_rejection_handler()).
    • Stack Traces: Include previous exceptions for nested Promise failures.
  • Monitoring:
    • Integrate with Laravel Horizon to track Promise-based queue jobs.
    • Add Sentry integration for error reporting.
  • Documentation:
    • Create internal docs for Laravel-specific Promise patterns (e.g., "How to chain queue jobs").
    • Example: Promise::race([$job1, $job2]) for timeout logic.

Scaling

  • Performance:
    • I/O-Bound: Near-zero overhead for async operations (e.g., HTTP, DB).
    • CPU-Bound: Avoid Promises for synchronous tasks (use native PHP).
  • Concurrency:
    • Parallelism: Promise.all() scales horizontally (e.g., batch API calls).
    • Cancellation: Use cancel() for long-running Promises (e.g., user-initiated timeouts).
  • Resource Usage:
    • Memory: Lightweight (no global state; Promises are immutable).
    • Threads: Single-threaded; safe for Laravel’s request lifecycle.

Failure Modes

Failure Scenario Mitigation
Unhandled Rejections Global handler logs to Laravel’s Log channel.
Memory Leaks Promises are garbage-collected; avoid circular references.
Timeouts Use Promise.race() with a timeout Promise (e.g., sleep(5)->then(...)).
Cancellation Issues Ensure cancel() is called in finally() blocks for cleanup.
PHP Version Incompatibility Pin to ^3.0 for PHP 8.1+; use v2.x for legacy.

Ramp-Up

  • Training:
    • Workshops: Teach Promise patterns (e.g., then/catch, all/race).
    • Code Reviews: Enforce Promise usage in async services.
  • **On
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.
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
spatie/mailcoach-vapor