Core, HTTP & Routing
Table of Contents
- Application
- Response
- Route Attribute
- RoutePrefix Attribute
- Middleware Attribute
- Built-in HTTP Middleware
Application
MonkeysLegion\Framework\Application
Central orchestrator — boots DI container, providers, and runs the HTTP or CLI kernel.
Properties
| Property | Type | Description |
|---|---|---|
$basePath | readonly string | Project root directory |
$environment | readonly string | Current env (production, staging, development, testing) |
$debug | readonly bool | Debug 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,
]);
| Param | Type | Description |
|---|---|---|
$providers | array<class-string<ServiceProviderInterface>> | Provider classes |
Returns: self (fluent)
withMiddleware(array $middleware): self
Prepend middleware to the HTTP pipeline.
$app->withMiddleware([
App\Middleware\CustomHeaderMiddleware::class,
]);
| Param | Type | Description |
|---|---|---|
$middleware | array<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),
]);
| Param | Type | Description |
|---|---|---|
$bindings | array<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);
| Param | Type | Default | Description |
|---|---|---|---|
$data | mixed | — | Any JSON-serializable value |
$status | int | 200 | HTTP status code |
$flags | int | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | json_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');
| Param | Type | Default | Description |
|---|---|---|---|
$path | string | — | Absolute file path on disk |
$filename | ?string | null | Download filename (defaults to basename) |
Throws: \InvalidArgumentException if path is not a readable file.
PSR-7 Methods
All standard PSR-7 ResponseInterface and MessageInterface methods:
| Method | Returns | Description |
|---|---|---|
getStatusCode() | int | HTTP status code |
withStatus(int $code, string $reason = '') | static | Clone with new status |
getReasonPhrase() | string | Status reason phrase |
getHeaders() | array | All headers |
hasHeader(string $name) | bool | Check header exists |
getHeader(string $name) | string[] | Header values |
getHeaderLine(string $name) | string | Comma-joined header values |
withHeader(string $name, $value) | static | Clone with replaced header |
withAddedHeader(string $name, $value) | static | Clone with appended header value |
withoutHeader(string $name) | static | Clone without header |
getBody() | StreamInterface | Response body stream |
withBody(StreamInterface $body) | static | Clone with new body |
getProtocolVersion() | string | HTTP protocol version |
withProtocolVersion(string $version) | static | Clone 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
| Param | Type | Default | Description |
|---|---|---|---|
$methods | string|string[] | — | HTTP verb(s): 'GET', ['GET','POST'] |
$path | string | '' | URI template with regex constraints: /users/{id:\d+} |
$name | string | '' | Named route for URL generation |
$summary | string | '' | OpenAPI summary |
$tags | string[] | [] | OpenAPI grouping tags |
$middleware | string[] | [] | Route-level middleware aliases |
$where | array<string,string> | [] | Parameter regex constraints |
$defaults | array<string,mixed> | [] | Default parameter values |
$domain | string | '' | Domain constraint |
$description | string | '' | Detailed OpenAPI description |
$meta | array<string,mixed> | [] | Additional metadata |
Instance Methods
| Method | Returns | Description |
|---|---|---|
hasMiddleware(string $middleware) | bool | Check for specific middleware |
getConstraint(string $param) | ?string | Get 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
| Param | Type | Description |
|---|---|---|
$prefix | string | URI 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
| Param | Type | Description |
|---|---|---|
$middleware | string[] | Middleware aliases or FQCNs |
Available Aliases
| Alias | Class |
|---|---|
auth | AuthenticationMiddleware |
cors | CorsMiddleware |
csrf | VerifyCsrfToken |
throttle | RateLimitMiddleware |
locale | LocaleMiddleware |
Built-in HTTP Middleware
All implement Psr\Http\Server\MiddlewareInterface.
| Class | Description |
|---|---|
ErrorHandlerMiddleware | Catches exceptions, renders error responses |
CorsMiddleware | Cross-Origin Resource Sharing headers |
SecurityHeadersMiddleware | Adds X-Frame-Options, X-Content-Type-Options, etc. |
RateLimitMiddleware | Request rate limiting (configurable via throttle:N,M) |
LoggingMiddleware | Logs request/response lifecycle |
ContentNegotiationMiddleware | Accept header parsing |
TimingMiddleware | Adds X-Response-Time header |
RequestIdMiddleware | Adds X-Request-Id header |
RequestSizeLimitMiddleware | Limits request body size |
ETagMiddleware | Automatic ETag generation for responses |
TrustedProxyMiddleware | Handles X-Forwarded-* headers behind load balancers |
IpFilterMiddleware | IP allowlist/blocklist filtering |
AuthMiddleware | HTTP-level authentication check |