HTTP Layer API

Comprehensive HTTP handling including request/response objects, routing, middleware, and kernel processing. These classes provide the foundation for handling web requests and generating responses in your Forge Engine applications.

Request

Represents an HTTP request and provides methods to access request data, headers, and other request-related information. This is the primary way to interact with incoming HTTP requests in your application.

Constructor & Properties

__construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], string $content = null)

Create a new Request instance with the given parameters.

// Create from globals
$request = Request::createFromGlobals();

// Create manually
$request = new Request(
    $_GET,
    $_POST,
    [],
    $_COOKIE,
    $_FILES,
    $_SERVER,
    file_get_contents('php://input')
);

Request Data Methods

get(string $key, mixed $default = null): mixed

Get a value from the query string (GET parameters).

$page = $request->get('page', 1);
$search = $request->get('search');

post(string $key, mixed $default = null): mixed

Get a value from the POST parameters.

$username = $request->post('username');
$email = $request->post('email', 'default@example.com');

input(string $key, mixed $default = null): mixed

Get a value from any input source (GET, POST, JSON).

$data = $request->input('user.name');
$settings = $request->input('settings', []);

all(): array

Get all input data as an array.

$allData = $request->all();
$filtered = $request->only(['name', 'email']);
$excluded = $request->except(['password', 'token']);

Request Information Methods

method(): string

Get the HTTP request method (GET, POST, PUT, DELETE, etc.).

if ($request->method() === 'POST') {
    // Handle POST request
}

isMethod(string $method): bool

Check if the request method matches the given method.

if ($request->isMethod('POST')) {
    // Handle POST request
}

url(): string

Get the full URL of the request.

$currentUrl = $request->url();
$fullUrl = $request->fullUrl(); // Includes query string

path(): string

Get the request path without the domain.

$path = $request->path(); // e.g., /users/123

Header Methods

header(string $key, string $default = null): string|null

Get a header value by key.

$contentType = $request->header('Content-Type');
$authToken = $request->header('Authorization');

bearerToken(): string|null

Get the bearer token from the Authorization header.

$token = $request->bearerToken();
if ($token) {
    // Validate JWT token
}

accepts(string|array $contentTypes): bool

Check if the request accepts the given content type(s).

if ($request->accepts('application/json')) {
    return response()->json($data);
}

Response

Represents an HTTP response and provides methods to set response data, headers, and status codes. This class is used to construct and send HTTP responses back to the client.

Constructor & Properties

__construct(mixed $content = '', int $status = 200, array $headers = [])

Create a new Response instance.

// Basic response
$response = new Response('Hello World', 200, ['Content-Type' => 'text/plain']);

// JSON response
$response = new Response(json_encode($data), 200, ['Content-Type' => 'application/json']);

Response Content Methods

setContent(mixed $content): self

Set the response content.

$response->setContent('Hello World');
$response->setContent(json_encode($data));

getContent(): string

Get the current response content.

$content = $response->getContent();

Status Code Methods

setStatusCode(int $code): self

Set the HTTP status code.

$response->setStatusCode(200); // OK
$response->setStatusCode(404); // Not Found
$response->setStatusCode(500); // Internal Server Error

getStatusCode(): int

Get the current status code.

$statusCode = $response->getStatusCode();

Header Methods

header(string $name, string $value): self

Set a response header.

$response->header('Content-Type', 'application/json');
$response->header('Cache-Control', 'no-cache');
$response->header('X-Custom-Header', 'value');

headers(array $headers): self

Set multiple headers at once.

$response->headers([
    'Content-Type' => 'application/json',
    'Cache-Control' => 'no-cache',
    'X-Rate-Limit' => '100'
]);

getHeaders(): array

Get all response headers.

$headers = $response->getHeaders();
foreach ($headers as $name => $value) {
    echo "$name: $value\n";
}

Response Helpers

json(mixed $data, int $status = 200): JsonResponse

Create a JSON response.

return response()->json(['message' => 'Success'], 200);
return response()->json($user, 201);

redirect(string $url, int $status = 302): RedirectResponse

Create a redirect response.

return response()->redirect('/dashboard');
return response()->redirect('/login', 301);

download(string $path, string $name = null): BinaryFileResponse

Create a file download response.

return response()->download('/path/to/file.pdf');
return response()->download('/path/to/file.pdf', 'custom-name.pdf');

Kernel

Handles HTTP request processing through middleware pipeline. The Kernel is responsible for processing incoming requests through the middleware stack and generating appropriate responses.

Core Methods

handle(Request $request): Response

Process a request through the middleware pipeline.

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

pushMiddleware(string $middleware): void

Add middleware to the pipeline.

$kernel->pushMiddleware(AuthenticationMiddleware::class);
$kernel->pushMiddleware(CorsMiddleware::class);
$kernel->pushMiddleware(RateLimitMiddleware::class);

getMiddleware(): array

Get all registered middleware.

$middleware = $kernel->getMiddleware();
foreach ($middleware as $class) {
    echo "Registered: $class\n";
}

Middleware

Interface for creating HTTP middleware. Middleware provides a convenient mechanism for filtering HTTP requests entering your application and processing responses before they're sent to the client.

Interface Definition

process(Request $request, callable $next): Response

Process an incoming request and return a response.

class AuthenticationMiddleware implements Middleware
{
    public function process(Request $request, callable $next): Response
    {
        // Before request handling
        if (!$this->authenticate($request)) {
            return new Response('Unauthorized', 401);
        }
        
        // Pass to next middleware
        $response = $next($request);
        
        // After request handling
        $response->header('X-Authenticated', 'true');
        
        return $response;
    }
}

Common Middleware Examples

CORS Middleware

class CorsMiddleware implements Middleware
{
    public function process(Request $request, callable $next): Response
    {
        $response = $next($request);
        
        $response->headers([
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => 'Content-Type, Authorization'
        ]);
        
        return $response;
    }
}

Rate Limit Middleware

class RateLimitMiddleware implements Middleware
{
    private $maxRequests = 100;
    private $window = 3600; // 1 hour
    
    public function process(Request $request, callable $next): Response
    {
        $key = 'rate_limit:' . $request->ip();
        $requests = $this->cache->get($key, 0);
        
        if ($requests >= $this->maxRequests) {
            return new Response('Rate limit exceeded', 429);
        }
        
        $this->cache->increment($key);
        $this->cache->expire($key, $this->window);
        
        return $next($request);
    }
}

Usage Examples

Common patterns and examples for working with the HTTP Layer classes.

Basic Request Handling

// Get current request
$request = Request::createFromGlobals();

// Access request data
$username = $request->post('username');
$email = $request->post('email');
$page = $request->get('page', 1);

// Check request method
if ($request->isMethod('POST')) {
    // Handle form submission
    $data = $request->all();
    
    // Validate input
    $validator = new Validator($data, [
        'username' => 'required|min:3',
        'email' => 'required|email'
    ]);
    
    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }
    
    // Process data
    $user = User::create($data);
    
    return response()->json(['user' => $user], 201);
}

JSON API Response

// Controller method
public function getUser(Request $request, $id)
{
    // Check if request wants JSON
    if (!$request->accepts('application/json')) {
        return response()->setContent('Unsupported format'), 406);
    }
    
    // Get user with authentication check
    $user = User::find($id);
    
    if (!$user) {
        return response()->json([
            'error' => 'User not found',
            'code' => 'USER_NOT_FOUND'
        ], 404);
    }
    
    // Check authorization
    if ($user->id !== $request->user()->id) {
        return response()->json([
            'error' => 'Unauthorized',
            'code' => 'UNAUTHORIZED'
        ], 403);
    }
    
    // Return success response
    return response()->json([
        'data' => $user->toArray(),
        'meta' => [
            'timestamp' => now()->toIso8601String(),
            'version' => '1.0'
        ]
    ], 200);
}

File Upload Handling

public function uploadFile(Request $request)
{
    // Validate file upload
    if (!$request->hasFile('document')) {
        return response()->json(['error' => 'No file uploaded'], 400);
    }
    
    $file = $request->file('document');
    
    // Validate file
    $validator = Validator::make(['file' => $file], [
        'file' => 'required|file|mimes:pdf,doc,docx|max:10240'
    ]);
    
    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }
    
    // Store file
    $path = $file->store('documents', 'local');
    
    // Create file record
    $document = Document::create([
        'name' => $file->getClientOriginalName(),
        'path' => $path,
        'size' => $file->getSize(),
        'mime_type' => $file->getMimeType()
    ]);
    
    return response()->json([
        'message' => 'File uploaded successfully',
        'document' => $document
    ], 201);
}

Best Practices

Recommended patterns and guidelines for working with the HTTP Layer.

Do's

  • • Always validate request data before processing
  • • Use appropriate HTTP status codes
  • • Set proper Content-Type headers
  • • Handle file uploads securely
  • • Use middleware for cross-cutting concerns
  • • Return consistent response formats
  • • Handle errors gracefully

Don'ts

  • • Don't trust user input without validation
  • • Don't expose sensitive information in responses
  • • Don't ignore HTTP method semantics
  • • Don't bypass middleware for security
  • • Don't return generic error messages
  • • Don't ignore content negotiation
  • • Don't store large files in memory