A request handler adaper for swoole, using PSR 7, PSR 15 and PSR 17.
- php: ^7.2
- ext-swoole: *
- dflydev/fig-cookies: ^2.0
- psr/http-factory: ^1.0.1
- psr/http-message: ^1.0.1
- psr/http-server-handler: ^1.0.1
Through Composer as chubbyphp/chubbyphp-swoole-request-handler.
This example uses zendframework/zend-diactoros.
<?php
declare(strict_types=1);
namespace App;
use Chubbyphp\SwooleRequestHandler\OnRequest;
use Chubbyphp\SwooleRequestHandler\PsrRequestFactory;
use Chubbyphp\SwooleRequestHandler\SwooleResponseEmitter;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoole\Http\Server;
use Zend\Diactoros\ResponseFactory;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\StreamFactory;
use Zend\Diactoros\UploadedFileFactory;
$loader = require __DIR__.'/vendor/autoload.php';
$responseFactory = new ResponseFactory();
$http = new Server('localhost', 8080);
$http->on('start', function (Server $server): void {
echo 'Swoole http server is started at http://localhost:8080'.PHP_EOL;
});
$http->on('request', new OnRequest(
new PsrRequestFactory(
new ServerRequestFactory(),
new StreamFactory(),
new UploadedFileFactory()
),
new SwooleResponseEmitter(),
new class($responseFactory) implements RequestHandlerInterface {
/**
* @var ResponseFactoryInterface
*/
private $responseFactory;
/**
* @param ResponseFactoryInterface $responseFactory
*/
public function __construct(ResponseFactoryInterface $responseFactory)
{
$this->responseFactory = $responseFactory;
}
/**
* @param ServerRequestInterface $request
*
* @return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
$response = $this->responseFactory->createResponse(200, 'OK');
$response->getBody()->write('It works!');
return $response;
}
}
));
$http->start();
Dominik Zogg 2019