Search code examples
phpasynchronousevent-drivenreactphp

Should an existing ReactPHP loop be reused?


Should a single ReactPHP loop be used for multiple purposes as shown below, or should a new loop be created and used for each purpose? If reused, the loop is obviously already running, so how does one ensure it is not inadvertently executed before completely configured such as in my process example (i.e. between $process->start($loop) and $process->stdout->on(...))?

<?php

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server('127.0.0.1:8080', $loop);

$socket->on('connection', function (React\Socket\ConnectionInterface $connection) use($loop) {
    $connection->on('data', function ($data) use ($connection, $loop) {

        $loop->addTimer(10, function() {
            syslog(LOG_INFO, 'Do something upon non-repeating timer completion');
        });

        $process = new \React\ChildProcess\Process($cmd);
        $process->start($loop);
        $process->stdout->on('data', function ($chunk) {
            syslog(LOG_INFO, 'Do something with $chunk');
        });

    });
});

$loop->run();

Solution

  • You should only use one loop and share it within your application. What I always do is first ensure everything is set up and then start the loop. You can do this with an event dispatcher like PSR-14 defines for example.