Skip to content

A request handler adapter for swoole, using PSR-7, PSR-15 and PSR-17.

License

Notifications You must be signed in to change notification settings

chubbyphp/chubbyphp-swoole-request-handler

Repository files navigation

chubbyphp-swoole-request-handler

Build Status Scrutinizer Code Quality Code Coverage Total Downloads Monthly Downloads Latest Stable Version Latest Unstable Version

Description

A request handler adaper for swoole, using PSR 7, PSR 15 and PSR 17.

Requirements

Installation

Through Composer as chubbyphp/chubbyphp-swoole-request-handler.

Usage

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();

Copyright

Dominik Zogg 2019

About

A request handler adapter for swoole, using PSR-7, PSR-15 and PSR-17.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages