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

React Functions Laravel Package

drift/react-functions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require drift/react-functions
    

    Requires PHP 8.1+ and ReactPHP (installed via react/event-loop).

  2. First Use Case: Convert a blocking function (e.g., file_get_contents) to non-blocking:

    use Drift\ReactFunctions\File;
    
    $loop = React\EventLoop\Factory::create();
    $file = new File($loop);
    
    $file->getContents('https://example.com')
        ->then(function ($contents) {
            echo $contents;
        })
        ->done();
    
  3. Where to Look First:

    • DOCS for function reference.
    • Demo for practical examples.
    • src/ for source code (e.g., File.php, Http.php).

Implementation Patterns

Core Workflows

  1. Replacing Blocking Calls: Replace synchronous functions (e.g., file_get_contents, curl_exec) with their non-blocking counterparts:

    use Drift\ReactFunctions\Http;
    
    $http = new Http($loop);
    $http->get('https://api.example.com/data')
        ->then(function ($response) {
            return json_decode($response, true);
        })
        ->then(function ($data) {
            // Process data asynchronously
        });
    
  2. Error Handling: Use .otherwise() for error cases:

    $file->getContents('invalid-url')
        ->otherwise(function ($error) {
            error_log("Failed to fetch: " . $error->getMessage());
        });
    
  3. Chaining Promises: Chain multiple async operations:

    $http->get('https://api.example.com/users')
        ->then(function ($users) {
            return $http->post('https://api.example.com/process', json_encode($users));
        })
        ->then(function ($result) {
            // Handle result
        });
    
  4. Integration with Laravel: Use React\EventLoop\LoopInterface via Laravel's service container:

    $loop = app(React\EventLoop\LoopInterface::class);
    $file = new File($loop);
    
  5. Custom ReactPHP Components: Extend existing functions (e.g., wrap a custom HTTP client):

    class CustomHttp extends Http {
        public function customGet($url) {
            return $this->get($url)->then(function ($response) {
                return strtoupper($response); // Example transformation
            });
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Blocking the Event Loop: Avoid mixing blocking calls (e.g., sleep(), file_get_contents without ReactPHP wrapper) in async code. Use the package's non-blocking methods instead.

  2. Promise Leaks: Always call .done() or .then() on promises to prevent memory leaks:

    // Bad: Unattached promise
    $file->getContents('url');
    
    // Good: Attach handlers
    $file->getContents('url')->done();
    
  3. PHP 8.1+ Required: Ensure your project uses PHP 8.1+ (or later) for compatibility with ReactPHP v3.

  4. Error Propagation: Unhandled promise rejections crash the event loop. Always use .otherwise() or .catch():

    $file->getContents('url')
        ->catch(function ($error) {
            // Handle error gracefully
        });
    

Debugging Tips

  1. Logging Promises: Use ->then() for debugging:

    $file->getContents('url')
        ->then(function ($contents) {
            logger()->debug("Contents:", ['data' => $contents]);
        });
    
  2. Timeouts: Add timeouts to prevent hanging:

    $promise = $file->getContents('url');
    $loop->addTimer(5, function () use ($promise) {
        $promise->cancel(); // Cancel after 5 seconds
    });
    
  3. Event Loop Inspection: Check for stuck loops with:

    $loop->futureTick(function () {
        logger()->debug("Loop is still running...");
    });
    

Extension Points

  1. Custom Functions: Extend the package by creating new classes (e.g., Drift\ReactFunctions\CustomFunction):

    namespace Drift\ReactFunctions;
    
    use React\Promise\PromiseInterface;
    
    class CustomFunction {
        public function __construct(private LoopInterface $loop) {}
    
        public function asyncTask($input): PromiseInterface {
            return new Promise(function ($resolve) {
                $this->loop->addTimer(1, function () use ($resolve, $input) {
                    $resolve($input * 2); // Example async task
                });
            });
        }
    }
    
  2. Middleware: Add middleware to promises for cross-cutting concerns (e.g., logging, retries):

    $promise->then(function ($result) {
        logger()->info("Operation succeeded", ['result' => $result]);
        return $result;
    });
    
  3. Configuration: Override defaults (e.g., timeout values) via dependency injection:

    $http = new Http($loop, [
        'timeout' => 10.0, // Default: 5.0 seconds
    ]);
    
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