velt/http

HTTP layer for Velt framework

Maintainers

Package info

github.com/Velt-PHP/veltphp-http

pkg:composer/velt/http

Transparency log

Statistics

Installs: 118

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 8

v0.1.1 2026-06-18 01:56 UTC

This package is not auto-updated.

Last update: 2026-08-14 02:04:17 UTC


README

velt/http is the web transport layer for Velt applications. It provides requests, responses, JSON responses, routing, controller dispatch, middleware pipelines, response normalization, sessions and CSRF foundations while relying on velt/kernel for application services.

Status: alpha. Routing and dispatch are functional; production hardening for proxies, uploads, streaming, rate limiting and security policy remains tracked in the repository milestone.

Installation

composer require velt/http:^0.1

Requirements: PHP 8.2+ and velt/kernel.

Register the HTTP layer

<?php

use Velt\Http\Integration\HttpServiceProvider;
use Velt\Kernel\Application;

$app = new Application(dirname(__DIR__));
$app->registerProvider(HttpServiceProvider::class);
$app->boot();

The service provider connects HTTP services to the application container without moving HTTP behavior into the kernel.

Define routes

<?php

use App\Users\Controllers\UserController;
use Velt\Http\JsonResponse;
use Velt\Http\Router;

return static function (Router $router): void {
    $router->get('/', static fn (): string => 'Velt');

    $router->get('/api/users/{id}', [UserController::class, 'show']);

    $router->post('/api/users', static fn (): JsonResponse =>
        JsonResponse::json(['created' => true], 201)
    );
};

Routes support parameter matching and route-specific middleware. A route under /api is treated as an API route by the current response normalization logic.

Request API

$request->method();
$request->path();
$request->query('page', 1);
$request->input('email');
$request->queries();
$request->inputs();
$request->header('content-type');
$request->allHeaders();
$request->isGet();
$request->isPost();

Requests normalize method, path, query/input collections and headers. Application validation must still enforce domain rules and reject unexpected values.

Responses

use Velt\Http\Response;
use Velt\Http\JsonResponse;

$html = new Response('<h1>Hello</h1>', 200, [
    'Content-Type' => 'text/html; charset=utf-8',
]);

$json = JsonResponse::json([
    'data' => ['id' => 10],
], 200);

ResponseInterface exposes status, headers, body and send behavior. ResponseFactory converts controller results and exceptions into consistent web or API responses. Controllers can return response objects, renderable values, JSON-compatible values or supported primitives.

Controller dispatch

final class UserController
{
    public function show(Request $request, string $id): JsonResponse
    {
        return JsonResponse::json([
            'data' => ['id' => $id],
        ]);
    }
}

The dispatcher matches the route, resolves controller instances through the container, passes route parameters and sends the result through the response factory.

Middleware

use Velt\Http\MiddlewareInterface;
use Velt\Http\Request;
use Velt\Http\ResponseInterface;

final class RequestIdMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next): ResponseInterface
    {
        $response = $next($request);

        return $response->header('X-Request-Id', bin2hex(random_bytes(8)));
    }
}

$route->middleware(RequestIdMiddleware::class);

Pipeline executes middleware in declared order and terminates at the route handler. Middleware should return a response and avoid hidden global state.

Sessions and CSRF

SessionStoreInterface supports get, set, has and remove. PhpSessionStore adapts PHP sessions. CsrfTokenManager creates, renders and validates CSRF tokens:

$token = $csrf->token();
echo $csrf->field();

if (!$csrf->validateRequest($request)) {
    throw new HttpException(419, 'CSRF token mismatch.');
}

Production applications must configure secure cookie attributes, HTTPS, session rotation and storage appropriate for their deployment. CSRF protects state-changing browser requests; API authentication requires a separate policy.

Error behavior

HttpException carries an HTTP status code. The response factory distinguishes API and web error formats. In production, diagnostics must never disclose stack traces, source paths, request secrets or database credentials.

Recommended API envelope:

{
  "success": false,
  "error": {
    "code": "resource_not_found",
    "message": "The requested resource does not exist."
  }
}

Front controller example

<?php

use Velt\Http\Dispatcher;
use Velt\Http\Request;

$kernel = require dirname(__DIR__) . '/bootstrap/app.php';

/** @var Dispatcher $dispatcher */
$dispatcher = $kernel['dispatcher'];
$response = $dispatcher->dispatch(Request::capture());
$response->send();

Current production checklist

Before Velt HTTP is considered stable, the project is completing:

  • trusted proxy and host validation;
  • CORS policy and preflight handling;
  • upload and stream contracts;
  • request/body/header size limits;
  • secure cookie/session defaults and identifier rotation;
  • rate limiting and resource protection;
  • content-negotiated error rendering;
  • malformed input, CRLF, traversal and fuzz tests;
  • concurrency and long-running runtime state isolation.

The native Android bridge does not use HTTP internally. HTTP remains a web and development-preview adapter, not a substitute for JNI.

Testing

composer install
vendor/bin/phpunit

The suite covers request accessors, responses, routing, dispatch, middleware pipeline and CSRF behavior. New features must include success and failure cases plus security-focused regression tests.

Contributing

Keep transport behavior in this repository and application/domain behavior outside it. Public changes require updated examples, stable error contracts and compatibility evidence with the kernel and skeleton.

License

MIT