Today I was implementing an HTTP Server using Swoole. At its core, the code looks just like the Swoole HTTP Server example:
<?php
$http = new \Swoole\HTTP\Server("127.0.0.1", 9501);
$http->on('request', function (\Swoole\HTTP\Request $request, \Swoole\HTTP\Response $response) {
// …
$response->end();
});
$http->start();
In that same project I was also looking to use a package that evolves around symfony/http-foundation
which:
- Takes in a
\Symfony\Component\HttpFoundation\Request
instance - Processes the
$request
to a\Symfony\Component\HttpFoundation\Response
- Returns the
$response
Instead of adjusting the processor to work with the \Swoole\HTTP\Request
and \Swoole\HTTP\Response
classes, I looked into converting the \Swoole\HTTP
classes to their \Symfony\Component\HttpFoundation
counterparts. That way the processor itself would remain untouched, and only some translation before and after would be done.
~
My solution lay into the indragunawan/swoole-http-message-bridge
package that provides just that. However, the package hadn’t been updated in two years and it was showing: It didn’t support symfony/http-foundation
version 5. Above that builds were failing.
Luckily for me those errors were easily fixable, and the author was kind enough to merge my two Pull Requests (#3 and #4) in only a few hours time 🙂
<?php
use Indragunawan\SwooleHttpMessageBridge\Symfony\Request as RequestFactory;
use Indragunawan\SwooleHttpMessageBridge\Symfony\Response as ResponseWriter;
$http = new \Swoole\HTTP\Server("127.0.0.1", 9501);
$http->on('request', function (\Swoole\HTTP\Request $request, \Swoole\HTTP\Response $response) {
// Convert the \Swoole\HTTP\Request instance into a \Symfony\Component\HttpFoundation\Request instance
$sfRequest = RequestFactory::createFromSwooleRequest($request);
// Process \Symfony\Component\HttpFoundation\Request, yielding a \Symfony\Component\HttpFoundation\Response
$sfResponse = …;
// Convert the \Symfony\Component\HttpFoundation\Response instance into a \Swoole\HTTP\Response instance and write it out to the client
ResponseWriter::writeSwooleResponse($response, $sfResponse);
});
$http->start();
Installation per Composer:
composer require indragunawan/swoole-http-message-bridge:^0.1.0
There’s a few more changes and additions that could be done to this package, but I’ll leave it at that for the time being 😉
~
Thank me with a coffee.
I don\'t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!
To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.