Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
PSR Response.
<?php
declare(strict_types=1);
use OpenSwoole\Core\Psr\Middleware\StackHandler;
use OpenSwoole\Core\Psr\Response;
use OpenSwoole\HTTP\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
$server = new Server('127.0.0.1', 9501);
$server->on('start', function (Server $server) {
echo "OpenSwoole http server is started at http://127.0.0.1:9501\n";
});
class DefaultResponseMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return (new Response('aaaa'))->withHeader('x-a', '1234');
}
}
class MiddlewareA implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$requestBody = $request->getBody();
var_dump('A1');
$response = $handler->handle($request);
var_dump('A2');
return $response;
}
}
class MiddlewareB implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$requestBody = $request->getBody();
var_dump('B1');
$response = $handler->handle($request);
var_dump('B2');
return $response;
}
}
$stack = (new StackHandler())
->add(new DefaultResponseMiddleware())
->add(new MiddlewareA())
->add(new MiddlewareB())
;
$server->handle(function ($request) use ($stack) {
return $stack->handle($request);
});
$server->start();