📦 Marketplace⭐ GitHub
API Referencev2.0

Core, HTTP & Routing

Table of Contents


Application

MonkeysLegion\Framework\Application

Central orchestrator — boots DI container, providers, and runs the HTTP or CLI kernel.

Properties

PropertyTypeDescription
$basePathreadonly stringProject root directory
$environmentreadonly stringCurrent env (production, staging, development, testing)
$debugreadonly boolDebug mode flag

Static Methods

create(string $basePath): self

Factory constructor. Entry point for the entire framework.

Application::create(basePath: dirname(__DIR__))->run();

Instance Methods

withProviders(array $providers): self

Register additional service providers.

$app->withProviders([
    App\Providers\PaymentProvider::class,
]);
ParamTypeDescription
$providersarray<class-string<ServiceProviderInterface>>Provider classes

Returns: self (fluent)


withMiddleware(array $middleware): self

Prepend middleware to the HTTP pipeline.

$app->withMiddleware([
    App\Middleware\CustomHeaderMiddleware::class,
]);
ParamTypeDescription
$middlewarearray<class-string>PSR-15 middleware classes

Returns: self (fluent)


withBindings(array $bindings): self

Register DI container bindings (interface → concrete).

$app->withBindings([
    CacheInterface::class => fn($c) => $c->get(RedisStore::class),
]);
ParamTypeDescription
$bindingsarray<string, callable|object>DI definitions

Returns: self (fluent)


run(): void

Boot the container and dispatch to the HTTP Kernel or CLI Kernel.

Application::create(basePath: dirname(__DIR__))
    ->withProviders([...])
    ->withMiddleware([...])
    ->run();

boot(): Container

Boot the DI container without dispatching. Useful for testing and CLI scripts.

Returns: MonkeysLegion\DI\Container


getContainer(): Container

Alias for boot().


Response

MonkeysLegion\Http\Message\Response implements Psr\Http\Message\ResponseInterface

Immutable PSR-7 Response with static named constructors.

Static Factories

json(mixed $data, int $status = 200, int $flags = ...): self

Create a JSON response.

return Response::json(['data' => $users], 200);
return Response::json(['error' => 'Not found'], 404);
ParamTypeDefaultDescription
$datamixedAny JSON-serializable value
$statusint200HTTP status code
$flagsintJSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHESjson_encode flags

Throws: \JsonException on encoding failure.


html(string $html, int $status = 200): self

Create an HTML response with Content-Type: text/html; charset=UTF-8.

return Response::html($this->renderer->render('home.index'));

text(string $text, int $status = 200): self

Create a plain-text response.

return Response::text('OK', 200);

noContent(): self

Create a 204 No Content response with empty body.

return Response::noContent();

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

Create a redirect response with Location header.

return Response::redirect('/login');         // 302
return Response::redirect('/new-url', 301);  // 301

download(string $path, ?string $filename = null): self

Create a file download response with Content-Disposition: attachment.

return Response::download('/storage/reports/q1.pdf');
return Response::download('/storage/data.csv', 'export.csv');
ParamTypeDefaultDescription
$pathstringAbsolute file path on disk
$filename?stringnullDownload filename (defaults to basename)

Throws: \InvalidArgumentException if path is not a readable file.


PSR-7 Methods

All standard PSR-7 ResponseInterface and MessageInterface methods:

MethodReturnsDescription
getStatusCode()intHTTP status code
withStatus(int $code, string $reason = '')staticClone with new status
getReasonPhrase()stringStatus reason phrase
getHeaders()arrayAll headers
hasHeader(string $name)boolCheck header exists
getHeader(string $name)string[]Header values
getHeaderLine(string $name)stringComma-joined header values
withHeader(string $name, $value)staticClone with replaced header
withAddedHeader(string $name, $value)staticClone with appended header value
withoutHeader(string $name)staticClone without header
getBody()StreamInterfaceResponse body stream
withBody(StreamInterface $body)staticClone with new body
getProtocolVersion()stringHTTP protocol version
withProtocolVersion(string $version)staticClone with new protocol version

Route Attribute

MonkeysLegion\Router\Attributes\Route

Defines HTTP routes on controller methods. Repeatable — a method can have multiple routes.

#[Route('GET', '/users', name: 'users.index')]
#[Route('POST', '/users', name: 'users.create')]

Constructor Parameters

ParamTypeDefaultDescription
$methodsstring|string[]HTTP verb(s): 'GET', ['GET','POST']
$pathstring''URI template with regex constraints: /users/{id:\d+}
$namestring''Named route for URL generation
$summarystring''OpenAPI summary
$tagsstring[][]OpenAPI grouping tags
$middlewarestring[][]Route-level middleware aliases
$wherearray<string,string>[]Parameter regex constraints
$defaultsarray<string,mixed>[]Default parameter values
$domainstring''Domain constraint
$descriptionstring''Detailed OpenAPI description
$metaarray<string,mixed>[]Additional metadata

Instance Methods

MethodReturnsDescription
hasMiddleware(string $middleware)boolCheck for specific middleware
getConstraint(string $param)?stringGet regex constraint for a route parameter

Path Syntax

/users                      → Static path
/users/{id}                 → Required parameter
/users/{id:\d+}             → Parameter with regex constraint
/posts/{slug?}              → Optional parameter
/files/{path:.+}            → Greedy match

RoutePrefix Attribute

MonkeysLegion\Router\Attributes\RoutePrefix

Prefixes all routes in a controller.

#[RoutePrefix('/api/v2/products')]
final class ProductApiController { ... }

Constructor

ParamTypeDescription
$prefixstringURI prefix applied to all methods in the class

Middleware Attribute

MonkeysLegion\Router\Attributes\Middleware

Apply route-level middleware to a controller class or individual method.

#[Middleware(['auth', 'throttle:60,1'])]
final class AdminController { ... }

Constructor

ParamTypeDescription
$middlewarestring[]Middleware aliases or FQCNs

Available Aliases

AliasClass
authAuthenticationMiddleware
corsCorsMiddleware
csrfVerifyCsrfToken
throttleRateLimitMiddleware
localeLocaleMiddleware

Built-in HTTP Middleware

All implement Psr\Http\Server\MiddlewareInterface.

ClassDescription
ErrorHandlerMiddlewareCatches exceptions, renders error responses
CorsMiddlewareCross-Origin Resource Sharing headers
SecurityHeadersMiddlewareAdds X-Frame-Options, X-Content-Type-Options, etc.
RateLimitMiddlewareRequest rate limiting (configurable via throttle:N,M)
LoggingMiddlewareLogs request/response lifecycle
ContentNegotiationMiddlewareAccept header parsing
TimingMiddlewareAdds X-Response-Time header
RequestIdMiddlewareAdds X-Request-Id header
RequestSizeLimitMiddlewareLimits request body size
ETagMiddlewareAutomatic ETag generation for responses
TrustedProxyMiddlewareHandles X-Forwarded-* headers behind load balancers
IpFilterMiddlewareIP allowlist/blocklist filtering
AuthMiddlewareHTTP-level authentication check