Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created May 29, 2024 06:55
Show Gist options
  • Save kobus1998/f49398f355ee73140747f2f77c20506d to your computer and use it in GitHub Desktop.
Save kobus1998/f49398f355ee73140747f2f77c20506d to your computer and use it in GitHub Desktop.
reactphp http server
<?php
use Laminas\Diactoros\Response\JsonResponse;
use League\Container\Container;
use League\Route\Router;
use League\Route\Strategy\ApplicationStrategy;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
require __DIR__ . '/vendor/autoload.php';
try {
$container = new Container;
$router = new Router();
$strategy = (new ApplicationStrategy);
$strategy->setContainer($container);
$router->setStrategy($strategy);
$router->get('/', function (ServerRequestInterface $request) {
return new JsonResponse(['abc' => 1]);
});
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) use ($router) {
try {
$response = $router->dispatch($request);
} catch (\League\Route\Http\Exception $e) {
return new Response(404, ['Content-Type' => 'application/json'], json_encode(['err' => 404]));
}
// turn laminas response into react response
return new Response($response->getStatusCode(), $response->getHeaders(), (string)$response->getBody());
});
// just to display exception
$http->on('error', function (Throwable $e) {
echo (string) $e, "\n";
});
$socket = new React\Socket\SocketServer('127.0.0.1:8080');
$http->listen($socket);
} catch (Throwable $e) {
echo (string) $e, "\n";
}
{
"require": {
"react/http": "^1.10.0",
"league/route": "^5.1",
"league/container": "^4.2",
"laminas/laminas-diactoros": "^3.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment