How to keep state in reactPHP server?

454 views Asked by At

ReachPHP server. Code for counting the number of requests:

$counter = 0;

$app = function ($request, $response) use ($counter){        
    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end($counter);
    $counter++;
};

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);

$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";

$socket->listen(1337);
$loop->run();

The counter remains 0 for every request, how can I make $counter variable persistent for all requests to the server ?

1

There are 1 answers

0
Grigory Ilizirov On BEST ANSWER

Just need to put &-sign before $counter to transfer by reference:

$counter = 0;

$app = function ($request, $response) use (&$counter){        
    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end($counter);
    $counter++;
};

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);

$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";

$socket->listen(1337);
$loop->run();

silly me...