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

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 capabilities (queues, jobs) by providing a composable Promise abstraction for orchestrating async workflows without forcing a full event loop. Ideal for scenarios where sequential/parallel async chaining is needed (e.g., API integrations, multi-step background jobs).
  • Hybrid Sync/Async: Bridges Laravel’s synchronous-by-default architecture with async patterns, enabling gradual adoption of async logic without rewriting core monolithic logic.
  • Library-Centric: Best suited for internal libraries, SDKs, or bounded contexts (e.g., a Services layer) where async orchestration is required but a heavy framework (ReactPHP, Amp) is unnecessary.

Integration Feasibility

  • Laravel Ecosystem Compatibility:
    • Queues/Jobs: Promises can wrap dispatch() calls or Bus jobs for chaining (e.g., Promise::all([job1(), job2()])).
    • HTTP Clients: Integrates with Guzzle/PestHTTP via adapters (e.g., GuzzlePromise::send()).
    • Events: Enables async event listeners (e.g., event1.then(() => event2)).
  • Dependency Minimalism: No event loop or heavy framework dependencies, reducing risk in monolithic apps.
  • PHP Version: Assumes PHP 8.1+ (aligned with Laravel’s LTS support), with no breaking changes in recent releases.

Technical Risk

  • No Native Async Execution: Promises must be resolved via callbacks, queues, or coroutines—not a drop-in replacement for async frameworks. Requires discipline to avoid blocking calls (e.g., Promise::then() with sync code).
  • Error Handling Complexity: PHP’s lack of native async/await means catch blocks still use callbacks, risking inconsistent error surfaces if misused.
  • Testing Overhead: Async flows require mocking (e.g., Mockery stubs for Promise::resolve()), increasing test complexity.
  • Performance Trade-offs: Overhead for high-throughput scenarios (e.g., batch Promise resolution) may need optimization (e.g., batching, worker pools).

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 unhandled rejections be caught (e.g., global handler, Sentry integration)?
    • Are there fallback mechanisms for critical failures (e.g., retry logic)?
  3. Adoption Scope:
    • Will Promises be used in core application logic (higher risk) or bounded contexts (e.g., API clients, background jobs)?
  4. Tooling Integration:
    • Can this integrate with Laravel Horizon (queue monitoring) or Telescope (Promise debugging)?
  5. Alternatives:
    • Could Laravel’s built-in Bus/Queue or PHP 8.1+ fibers suffice, or is a Promise layer necessary for composability?

Integration Approach

Stack Fit

  • Primary Use Cases in Laravel:
    • API Clients: Chain HTTP requests (e.g., Promise::all([userApi(), ordersApi()])).
    • Queue Workers: Orchestrate dependent jobs (e.g., Promise::then() for post-job processing).
    • Event-Driven Logic: Compose async event handlers (e.g., event1.then(() => event2)).
  • Laravel Synergy:
    • 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::promise($job)).
    • Testing: Use Mockery to stub Promise resolutions in PHPUnit tests.

Migration Path

  1. Pilot Phase (0–2 weeks):
    • Replace nested callbacks in a single feature (e.g., async API integration) with Promise chains.
    • Example: Convert Guzzle->then() to Promise::resolve(Guzzle->send())->then().
  2. Core Integration (2–4 weeks):
    • Create Promise wrappers for Laravel Queues (Promise::dispatch($job)).
    • Add combinator utilities (e.g., Promise::race(), Promise::allSettled()).
  3. Tooling (4+ weeks):
    • Integrate with Telescope for Promise state logging.
    • Add Laravel Forge/Envoyer hooks for async worker warm-up.

Compatibility

  • Laravel Ecosystem:
    • Queues: Promises can wrap dispatch() but won’t replace the queue system (still need workers).
    • HTTP Clients: Works with Guzzle/PestHTTP via custom adapters (e.g., GuzzlePromise::send()).
    • Events: Bridges Event::dispatch() with Promises for async listeners.
  • 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).

Sequencing

  1. Phase 1 (0–2 weeks):
    • Implement Promises for critical async paths (e.g., API integrations, queue jobs).
    • Add basic error handling and logging.
  2. Phase 2 (2–4 weeks):
    • Extend to event listeners and custom commands.
    • Build combinator utilities (e.g., Promise::allSettled()).
  3. Phase 3 (4+ weeks):
    • Integrate with monitoring (Telescope/Sentry).
    • Document patterns for team adoption (e.g., "Avoid Promise leaks").

Operational Impact

Maintenance

  • Pros:
    • Lightweight: Minimal core means lower maintenance overhead.
    • Isolated Scope: If scoped to libraries/services, changes won’t disrupt the entire app.
  • Cons:
    • Async Debugging: Harder to trace Promise chains in production (requires Telescope/Xdebug async support).
    • Team Familiarity: Requires upskilling on Promise patterns (e.g., avoiding "unhandled rejection" pitfalls).

Support

  • Developer Experience:
    • Readability: Reduces callback nesting but introduces new concepts (e.g., .then() chaining).
    • Onboarding: Need clear docs/examples for:
      • Resolving Promises in Laravel’s sync context.
      • Handling edge cases (e.g., circular dependencies, memory leaks).
  • Production Issues:
    • Common Failure Modes:
      • Unhandled rejections crashing workers (mitigate with global handlers).
      • Memory leaks from unresolved Promises (use finally for cleanup).
    • Rollback Plan: If adoption stalls, revert to callbacks or use Laravel’s native async tools.

Scaling

  • Performance:
    • Not a Silver Bullet: Promises alone don’t parallelize work (still need Queues/Workers).
    • Bottlenecks: Inefficient combinators (e.g., Promise::all() with many slow operations) may need batching.
  • Horizontal Scaling:
    • Works well with Laravel’s queue workers (e.g., scale Promises across pods).
    • Avoid global Promise state (e.g., shared resolvers) in distributed setups.

Failure Modes

Failure Scenario Impact Mitigation
Unhandled Promise rejection Silent crashes or partial failures Global set_unhandled_rejection_handler()
Circular Promise dependencies Memory leaks or deadlocks Static analysis tools (e.g., Psalm)
Queue worker crashes Broken async flows Retry logic + Sentry alerts
Promise leak (unresolved) Memory bloat finally blocks or TTL for Promises
Mixed sync/async code Race conditions Clear architecture boundaries (e.g., "Promises only in X layer")

Ramp-Up

  • Training:
    • Workshops: Hands-on sessions converting callback-heavy code to Promises.
    • Code Reviews: Enforce Promise best practices (e.g., no nested .then() chains).
  • Documentation:
    • Cheat Sheet: Common patterns (e.g., "How to retry a failed Promise").
    • Decision Records: Justify why Promises were chosen over alternatives (e.g., Queues alone).
  • Tooling:
    • IDE Support: PHPStorm/Xdebug for Promise debugging.
    • Testing: Example test cases for Promise mocking (e.g., Promise::resolve() stubs).
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style