Reflection API for Swoole web-server

1.3.0 2019-05-25 02:10 UTC


This library provides a Reflection API for classes of Swoole web-server.


  • Server middleware manipulation
  • Response lifecycle tracking


The library is to be installed via Composer as a dependency:

composer require upscale/swoole-reflection


Middleware Manipulation

Override server middleware optionally reusing the original callback:

class MiddlewareExample
    public function __invoke($request, $response)
        $response->end("Served by Swoole server\n");

$server = new \Swoole\Http\Server('', 8080);
$server->on('request', new MiddlewareExample());

$reflection = new \Upscale\Swoole\Reflection\Http\Server($server);
$middleware = $reflection->getMiddleware();
$reflection->setMiddleware(function ($request, $response) use ($middleware) {
   $response->header('Content-Type', 'text/plain');
   $middleware($request, $response);


Response Lifecycle

Headers Tracking

Modify response headers before they have been sent:

$server->on('request', function ($request, $response) {
    $response = new \Upscale\Swoole\Reflection\Http\Response\Observable($response);
    $response->onHeadersSentBefore(function () use ($request, $response) {
        $response->header('Content-Type', 'text/plain');
    $response->end("Served by Swoole server\n");

Callback is invoked once per request upon the first call to \Swoole\Http\Response::write/end/sendfile() methods.

Body Interception

Modify response body before sending it out:

$server->on('request', function ($request, $response) use ($server) {
    $response = new \Upscale\Swoole\Reflection\Http\Response\Observable($response);
    $response->onBodyAppend(function (&$content) use ($server) {
        $content .= "<!-- Served by worker {$server->worker_id} -->\n";
    $response->header('Content-Type', 'text/html');
    $response->end("Served by <b>Swoole server</b>\n");

Callback is invoked on every call to \Swoole\Http\Response::write/end() methods with non-empty content.


Pull Requests with fixes and improvements are welcome!


Copyright © Upscale Software. All rights reserved.

Licensed under the Apache License, Version 2.0.