Skip to content

Omega MVC — Http Package Manual ​

The Omega\Http package provides the full HTTP layer: request encapsulation, response building, middleware pipeline execution, JSON/redirect/streamed responses, file uploads, header management, URL parsing, and RoadRunner persistent-worker integration. It also includes PSR-7 bridge adapters.

Installation ​

The package ships with the framework and is autoloaded via Composer:

bash
composer require omega-mvc/framework

Http kernel ​

Http is the central kernel that handles the full HTTP request/response lifecycle: bootstrapping, route dispatch, middleware execution, exception handling, and termination.

php
use Omega\Http\Http;
use Omega\Http\Request;
use Omega\Http\Response;

$kernel  = new Http($app);
$request = RequestFactory::capture();

$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

API reference — Http ​

MethodReturnDescription
__construct(ApplicationInterface $app)—Inject the application container
handle(Request $request): ResponseResponseProcess a request through bootstrap, dispatch, and middleware
bootstrap(): voidvoidExecute registered bootstrapper classes
terminate(Request $request, Response $response): voidvoidRun terminate callbacks on middleware, then reset per-request state

Bootstrappers ​

Executed in order during bootstrap():

BootstrapperPurpose
ConfigBootstrapperLoad application configuration
HandleExceptionsRegister error/exception/shutdown handlers
FacadeBootstrapperInitialize facade bindings
RegisterProvidersRegister service providers
BootProvidersBoot registered service providers

Global middleware ​

Applied to every request by default:

MiddlewarePurpose
MaintenanceMiddlewareCheck maintenance mode
StartSessionMiddlewareStart session for the request
CsrfMiddlewareCSRF token validation

Middleware pipeline ​

Middleware is executed in reverse order (onion model). Each middleware must expose a handle(Request $request, callable $next): Response method:

php
class MyMiddleware
{
    public function handle(Request $request, callable $next): Response
    {
        // Before logic
        $response = $next($request);
        // After logic
        return $response;
    }
}

The terminate() method is called on each middleware after the response has been sent, allowing cleanup work:

php
class MyMiddleware
{
    public function terminate(Request $request, Response $response): void
    {
        // Post-response cleanup
    }
}

Persistent worker support ​

Http marks the request as request-scoped via setRequestScoped(). The resetForRequest() method clears request-scoped container state, rolls back dangling database transactions, and resets static Router/Facade state between requests in persistent workers (e.g. RoadRunner).

Request ​

Request encapsulates all aspects of an HTTP request. Implements ArrayAccess and IteratorAggregate for convenient input access.

php
$request = RequestFactory::capture();

// Access input
$value = $request->input('name');
$query = $request->getQuery('page');
$post  = $request->getPost('email');

// Array access
$value = $request['name'];

// JSON body
$json = $request->json();

// Headers
$auth = $request->getAuthorization();
$token = $request->getBearerToken();

// Request properties
$method = $request->getMethod();       // GET, POST, etc.
$url    = $request->getUrl();
$ip     = $request->getRemoteAddress();
$isJson = $request->isJson();
$isAjax = $request->isAjax();
$isHttps = $request->isSecured();

API reference — Request ​

MethodReturnDescription
__construct(string $url, array $query, array $post, ...)—Create a new request
initialize(...): selfselfRe-initialize all request data
duplicate(?array $query, ?array $post, ...): selfselfClone with optional overrides
getUrl(): stringstringGet the requested URL
getQuery(?string $key = null): array|stringarray|stringGet $_GET values
getPost(?string $key = null): array|stringarray|stringGet $_POST values
getFile(?string $key = null): arrayarrayGet uploaded files
getCookie(string $key): ?string?stringGet a cookie value
getCookies(): ?array?arrayGet all cookies
getMethod(): stringstringGet the HTTP method (uppercase)
isMethod(string $method): boolboolCheck the HTTP method
getHeaders(?string $header = null): array|string|nullmixedGet request headers
getMimeTypes(string $format): arrayarrayGet MIME types for a format
getFormat(?string $mimeType): ?string?stringGet format for a MIME type
getRequestFormat(): ?string?stringDetect format from Content-Type
isHeader(string $headerKey, string $headerVal): boolboolCheck header value
hasHeader(string $header_key): boolboolCheck header existence
isSecured(): boolboolCheck HTTPS
getRemoteAddress(): stringstringGet client IP
getRawBody(): ?string?stringGet raw request body
getJsonBody(): arrayarrayDecode JSON body as array
getAttribute(string $key, mixed $default): mixedmixedGet a custom attribute
with(array $pushAttributes): selfselfMerge custom attributes
all(): arrayarrayGet all request data merged
wrap(): arrayarrayGet all data in a single-element array
isAjax(): boolboolCheck XMLHttpRequest header
isJson(): boolboolCheck JSON content type
json(): CollectionCollectionGet JSON body as a Collection
getAuthorization(): ?string?stringGet Authorization header
getBearerToken(): ?string?stringExtract Bearer token
input(?string $key = null, ?string $default = null): Collection|stringmixedGet input (auto-detects source)
query(): CollectionImmutableCollectionImmutableImmutable query collection
post(): CollectionImmutableCollectionImmutableImmutable POST collection

Magic property access ​

Request implements __get() to read input values dynamically:

php
$page = $request->query_1; // equivalent to $request->input('query_1')

Macro methods ​

Request uses MacroableTrait. The following macros are registered by MacroServiceProvider:

MethodReturnDescription
validate(?Closure $rule, ?Closure $filter): ValidatorValidatorRun validation against all input data
upload(string $fileName): UploadFileUploadFileRetrieve an uploaded file by input name
php
// Validate all input
$validator = $request->validate(function ($rule) {
    $rule->field('email')->required()->email();
    $rule->field('name')->required()->min(3);
});

// Retrieve an uploaded file
$file = $request->upload('avatar');
$file->setFolderLocation(storage_path('uploads/'));
$file->setFileTypes(['jpg', 'jpeg', 'png']);
$file->setMaxFileSize(2_000_000);
$destination = $file->upload();

Response ​

Response represents an HTTP response with status code, headers, content, and protocol version.

php
$response = new Response('Hello, world!', 200);
$response->send();

// JSON response
$response = new Response(['message' => 'ok']);
$response->json()->send();

// Redirect
$response = new Response();
$response->setResponseCode(302);
$response->header('Location', '/dashboard');
$response->send();

Status code constants ​

ConstantValue
HTTP_OK200
HTTP_CREATED201
HTTP_ACCEPTED202
HTTP_NO_CONTENT204
HTTP_MOVED_PERMANENTLY301
HTTP_BAD_REQUEST400
HTTP_UNAUTHORIZED401
HTTP_FORBIDDEN403
HTTP_NOT_FOUND404
HTTP_METHOD_NOT_ALLOWED405

API reference — Response ​

MethodReturnDescription
__construct(array|string $content = '', int $responseCode = 200, array $headers = [])—Create a response
send(): selfselfSend headers and content to the client
json(array|string|null $content = null): selfselfSet content type to JSON
html(bool $minify = false): selfselfSet content type to HTML (optional minification)
plainText(): selfselfSet content type to plain text
setContent(string|array $content): selfselfSet response content
setResponseCode(int $responseCode): selfselfSet the HTTP status code
setHeaders(array $headers): selfselfReplace all headers
setProtocolVersion(string $version): selfselfSet HTTP version
setContentType(string $contentType): selfselfSet Content-Type header
header(string $header, ?string $value = null): selfselfAdd/set a header
getHeaders(): arrayarrayGet all headers
getStatusCode(): intintGet the status code
getContent(): string|arraymixedGet response content
getProtocolVersion(): stringstringGet HTTP version
getContentType(): stringstringGet Content-Type
followRequest(Request $request, array $headerName = []): selfselfCopy headers from a request
removeHeader(string|array $headers): selfselfMark headers for removal
removeHeaders(array $headers): selfselfMark multiple headers for removal
removeDefaultHeader(bool $removeDefaultHeader): selfselfRemove default server headers
isInformational(): boolboolCheck if 1xx
isSuccessful(): boolboolCheck if 2xx
isRedirection(): boolboolCheck if 3xx
isClientError(): boolboolCheck if 4xx
isServerError(): boolboolCheck if 5xx
close(): voidvoidExit the application

Static methods ​

MethodDescription
closeOutputBuffers(int $targetLevel, bool $flush): voidFlush or clean output buffers to a target level

JsonResponse ​

Extends Response. Automatically encodes data to JSON and sets the Content-Type header.

php
use Omega\Http\JsonResponse;

$response = new JsonResponse(['status' => 'ok'], 200);
$response->setEncodingOptions(JSON_PRETTY_PRINT);
$response->send();

API reference — JsonResponse ​

MethodReturnDescription
__construct(?array $data = null, int $statusCode = 200, array $headers = [])—Create a JSON response
setEncodingOptions(int $encodingOptions): selfselfSet JSON encoding options
getEncodingOptions(): intintGet encoding options
setJson(string $json): selfselfSet raw JSON string
setData(mixed $data): selfselfEncode data as JSON
getData(): arrayarrayGet decoded JSON data

RedirectResponse ​

Extends Response. Sets the Location header and generates an HTML page with a meta-refresh redirect.

php
use Omega\Http\RedirectResponse;

$response = new RedirectResponse('/dashboard');
// $response->send();
MethodReturnDescription
__construct(string $url, int $responseCode = 302, array $headers = [])—Create a redirect response
setTarget(string $url): voidvoidUpdate the redirect URL

StreamedResponse ​

Extends Response. Streams content to the client via a callback, useful for large files or real-time output.

php
use Omega\Http\StreamedResponse;

$response = new StreamedResponse(function () {
    echo "Line 1\n";
    flush();
    echo "Line 2\n";
    flush();
});
$response->send();
MethodReturnDescription
__construct(?callable $callableStream, int $responseCode = 200, array $headers = [])—Create a streamed response
setStream(?callable $callableStream): selfselfSet/replace the stream callback

HeaderCollection ​

Extends Collection. Manages HTTP headers with support for parsing, modifying, and rendering directive values (e.g. Cache-Control: max-age=3600, public).

php
use Omega\Http\HeaderCollection;

$headers = new HeaderCollection(['Content-Type' => 'text/html']);
$headers->set('X-Custom', 'value');
$headers->addDirective('Cache-Control', ['max-age' => '3600']);
$raw = (string) $headers; // "Content-Type: text/html\r\nX-Custom: value\r\n..."

API reference — HeaderCollection ​

MethodReturnDescription
__toString(): stringstringRender as raw HTTP header string
setRaw(string $header): selfselfParse and set a raw "Name: value" header
getDirective(string $header): arrayarrayParse a header into directives
addDirective(string $header, array $value): selfselfAdd directives to a header
removeDirective(string $header, string $item): selfselfRemove a directive from a header
hasDirective(string $header, string $item): boolboolCheck if a directive exists

Url ​

Parses a URL string and provides typed access to its components.

php
use Omega\Http\Url;

$url = Url::parse('https://user:pass@example.com:8080/path?q=1#section');
$url->schema();    // 'https'
$url->host();      // 'example.com'
$url->port();      // 8080
$url->user();      // 'user'
$url->password();  // 'pass'
$url->path();      // '/path'
$url->query();     // ['q' => '1']
$url->fragment();  // 'section'

// From a Request
$url = Url::fromRequest($request);

Helper functions ​

FunctionDescription
redirect(string $url): RedirectResponseCreate a redirect response to a URL
redirect_route(string $route_name, array $parameter = []): RedirectResponseRedirect to a named route

RequestFactory ​

Factory for creating Request instances from PHP globals or PSR-7 objects.

php
use Omega\Http\RequestFactory;

// From PHP superglobals
$request = RequestFactory::capture();

// From PSR-7 (RoadRunner, etc.)
$request = RequestFactory::fromPsr7ServerRequest($psr7Request);
MethodReturnDescription
capture(): RequestRequestBuild a Request from $_GET, $_POST, etc.
fromPsr7ServerRequest(ServerRequestInterface $psr7): RequestRequestBuild a Request from a PSR-7 object

ResponseFactory ​

Converts an Omega Response into a PSR-7 ResponseInterface.

php
use Omega\Http\ResponseFactory;

$psr7 = ResponseFactory::toPsr7($response, $psr7Factory, $streamFactory);

RoadRunner integration ​

RoadRunnerWorker ​

Bridges the Omega Http kernel to a RoadRunner persistent worker. Each PSR-7 request is converted to an Omega Request, handled, converted back to a PSR-7 response, and sent to the client.

php
use Omega\Http\Http;
use Omega\Http\RoadRunnerWorker;

$worker = new RoadRunnerWorker(
    $http,
    psr7Factory: $psr17Factory,
    streamFactory: $psr17StreamFactory
);

$worker->run($responder);

RoadRunnerResponderInterface ​

Contract for the RoadRunner PSR-7 responder (canonical implementation: Spiral\RoadRunner\Http\PSR7Worker).

MethodDescription
waitRequest(): ServerRequestInterface|false|nullWait for the next request
respond(ResponseInterface $response): voidSend a response back to the client

File uploads ​

UploadFile (single file) ​

php
use Omega\Http\Upload\UploadFile;

$file = new UploadFile($_FILES['avatar']);
$file->setFolderLocation(storage_path('uploads/'));
$file->setFileName('profile');
$file->setFileTypes(['jpg', 'jpeg', 'png']);
$file->setMaxFileSize(2_000_000);

$destination = $file->upload(); // string path or empty string on failure
$content     = $file->get();    // file contents (after successful upload)
$success     = $file->success();
$error       = $file->getError();

UploadMultiFile (multiple files) ​

php
use Omega\Http\Upload\UploadMultiFile;

$files = new UploadMultiFile($_FILES['documents']);
$files->setFolderLocation(storage_path('uploads/'));
$files->setFileName('doc');
$files->setFileTypes(['pdf', 'docx']);
$files->setMaxFileSize(5_000_000);

$destinations = $files->uploads(); // string[] of paths
$contents     = $files->getAll();  // string[] of contents

AbstractUpload API ​

MethodDescription
success(): boolWhether the upload succeeded
getError(): stringHuman-readable error message
getFileTypes(): arrayAllowed file extensions
setFileName(string $fileName): selfSet base file name (without extension)
setFolderLocation(string $folderLocation): selfSet destination directory
setFileTypes(array $extensions): selfSet allowed extensions
setMimeTypes(array $mimes): selfSet allowed MIME types
setMaxFileSize(int $byte): selfSet max file size in bytes
markTest(bool $markUploadTest): selfEnable test mode (uses copy() instead of move_uploaded_file())
delete(string $url): boolDelete a file from disk
creatFolder(string $path): boolCreate a directory recursively

Exceptions ​

ExceptionBase classThrown when
HttpExceptionRuntimeExceptionHTTP error with status code, message, and optional headers
HttpResponseExceptionRuntimeExceptionA Response object is returned as an exception
FileNotUploadedExceptionRuntimeExceptionAttempting to read a file that was not uploaded
FileNotExistsExceptionInvalidArgumentExceptionReferenced file does not exist on disk
FolderNotExistsExceptionInvalidArgumentExceptionReferenced folder does not exist on disk
MultiFileUploadDetectExceptionInvalidArgumentExceptionMulti-file data passed to UploadFile instead of UploadMultiFile
StreamedResponseCallableExceptionExceptionStreamedResponse invoked without a callback

HttpException ​

php
use Omega\Http\Exceptions\HttpException;

throw new HttpException(
    statusCode: 422,
    message: 'Validation failed',
    previous: null,
    headers: ['X-Error-Field' => 'email']
);

// Accessible via:
$e->getStatusCode(); // 422
$e->getHeaders();    // ['X-Error-Field' => 'email']

Notes ​

  • Response::send() calls fastcgi_finish_request() or litespeed_finish_request() when available, to finalize the connection before running terminate callbacks.
  • Request implements ArrayAccess using the input source (query, post, or JSON body), so $request['key'] works seamlessly.
  • RequestFactory::fromPsr7ServerRequest() supports method override via the X-HTTP-Method-Override header on POST requests.
  • Upload classes default to jpg/jpeg/png extensions and 50 KB max size; always configure these before calling upload().

Reference ​

  • Source: src/Omega/Http/
  • Tests: tests/Unit/Http/
  • License: GPL-3.0+