0

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();
user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

1

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.

WyriHaximus
  • 1,000
  • 6
  • 8
  • Thanks WyriHaximus, Normally, I always set up first then start, but I need to start a timer and perform some child process after some event happens. Thanks for the pointer to PSR-14 event dispatcher. – user1032531 Jun 12 '19 at 13:41
  • That's essentially how ReactPHP works:you're responding to events. The event loop is designed to keep running as long as you give it something to do. So adding new stuff like a child process to it while running is perfectly valid and intended behaviour. In fact the socket server internally adds all new incoming connections to the event loop to be able to read & write from & to it. The PSR-14 mention is an example, do what fits your architecture and vision best. – WyriHaximus Jun 12 '19 at 13:54