PHP code example of leocavalcante / request-callback

1. Go to this page and download the library: Download leocavalcante/request-callback library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

leocavalcante / request-callback example snippets


use Swoole\Http\RequestCallback;

$callback = new RequestCallback(\Psr\Http\Server\RequestHandlerInterface);

use Laminas\Diactoros\Response\TextResponse;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Psr\Http\Server\RequestHandlerInterface;
use Swoole\Http\{RequestCallback, Server};

$server = new Server('localhost', 9501);

$server->on('request', new RequestCallback(new class implements RequestHandlerInterface {
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new TextResponse(sprintf('Hello, %s!', $request->getQueryParams()['name'] ?? 'World'));
    }
}));

$server->start();

$server->on('request', RequestCallback::fromCallable(static function (ServerRequestInterface $request): ResponseInterface {
    return new TextResponse(sprintf('Hello, %s!', $request->getQueryParams()['name'] ?? 'World'));
}));

$server->on('request', request_callback(
    static fn(ServerRequestInterface $request): ResponseInterface =>
        new TextResponse(sprintf('Hello, %s!', $request->getQueryParams()['name'] ?? 'World')))
);


use Laminas\Diactoros\Response\JsonResponse;
use Laminas\Stratigility\MiddlewarePipe;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Psr\Http\Server\RequestHandlerInterface;
use Swoole\Http\{RequestCallback, Server};
use function Laminas\Stratigility\middleware;

$app = new MiddlewarePipe();

$app->pipe(middleware(static function (ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface {
    $user = $request->getQueryParams()['user'] ?? null;

    if ($user === null) {
        return new JsonResponse(['error' => true, 'message' => 'Unauthorized'], 401);
    }

    return $next
        ->handle($request->withAttribute('user', $user))
        ->withAddedHeader('X-Foo', 'Bar');
}));

$app->pipe(middleware(static function (ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface {
    return new JsonResponse(['message' => sprintf('Hello, %s!', $request->getAttribute('user'))]);
}));

$server = new Server('0.0.0.0', 9501);
$server->on('request', new RequestCallback($app));
$server->start();