upscale / swoole-reflection
Reflection API for Swoole web-server
Installs: 110 018
Dependents: 5
Suggesters: 0
Security: 0
Stars: 2
Watchers: 3
Forks: 1
Open Issues: 1
Requires
- php: >=8.0
- upscale/ext-openswoole: ^4.8||^22.0
- upscale/ext-swoole: ^5.0
Requires (Dev)
- ext-curl: *
- phpunit/phpunit: ^9.5
- upscale/swoole-launchpad: ^2.0
README
This library provides a Reflection API for classes of Swoole / Open Swoole web-server.
Features:
- Server middleware manipulation
- Response lifecycle tracking
Installation
The library is to be installed via Composer as a dependency:
composer require upscale/swoole-reflection
Usage
Middleware Manipulation
Override server middleware optionally reusing the original callback:
$server = new \Swoole\Http\Server('127.0.0.1', 8080); $server->on('request', function ($request, $response) { $response->end("Served by Swoole server\n"); }); $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); }); $server->start();
Response Lifecycle
Headers Tracking
Modify response headers before they have been sent:
$server->on('request', function ($request, $response) { $callback = function () use ($request, $response) { $response->header('Content-Type', 'text/plain'); }; $response = new \Upscale\Swoole\Reflection\Http\Response\Observable($response); $response->onHeadersSentBefore($callback); $response->end("Served by Swoole server\n"); });
Callback is invoked on every request upon the first call to \Swoole\Http\Response::write/end/sendfile()
.
Warning! Callbacks that need to modify response must use the original response rather than its observable proxy.
Dependency on observable proxy creates circular reference between the proxy and callbacks registered within it.
Instances involved in orphan circular cross-references will not be destroyed until the next garbage collection cycle.
Swoole calls \Swoole\Http\Response::end()
in the response destructor executed upon the request completion.
The response destructor will not be called causing the the worker to hang up without sending the response.
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()
with non-empty contents.
Contributing
Pull Requests with fixes and improvements are welcome!
License
Copyright © Upscale Software. All rights reserved.
Licensed under the Apache License, Version 2.0.