Repository navigation
Configuration
The third constructor argument is a configuration array. Every key is optional.
use InitPHP\Router\Router;
$router = new Router($request, $response, [
'paths' => [
'controller' => null, // Absolute path to the controller directory.
'middleware' => null, // Absolute path to the middleware directory.
],
'namespaces' => [
'controller' => null, // Namespace prefix for controller classes.
'middleware' => null, // Namespace prefix for middleware classes.
],
'base_path' => '/', // Sub-directory the app runs in.
'variable_method' => false, // Enable the $_REQUEST['_method'] override.
'argument_new_instance' => false, // Inject fresh request/response instances.
// Optional integrations:
'container' => $psr11Container, // A PSR-11 ContainerInterface.
'cache' => [
'enable' => false,
'path' => null, // File for the compiled route table.
'ttl' => 86400, // Seconds.
],
]);Used to locate controller and middleware classes referenced by short name. See Controllers and Middleware.
If the app is served from a sub-directory (e.g. https://host/app/), set
base_path to '/app' so route paths match relative to it. The default '/'
means the app runs at the domain root.
When true, the HTTP method can be overridden with a _method request
parameter — useful for HTML forms, which can only send GET/POST:
$router = new Router($request, $response, ['variable_method' => true]);
$router->put('/articles/{id}', 'ArticleController@update');<form method="post" action="/articles/42">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
</form>The override is only honoured when the value is one of the supported methods.
Check the token before the handler changes anything, in the handler or in a middleware (the session must be started and hold the token you rendered into the form):
function assertValidCsrfToken(): void
{
$expected = (string) ($_SESSION['csrf_token'] ?? '');
$sent = (string) ($_POST['csrf_token'] ?? ''); // request body only, never the query string
if ($expected === '' || !hash_equals($expected, $sent)) {
http_response_code(403);
exit('Invalid CSRF token.');
}
}Warning: the override also applies to
GETrequests. The router reads_methodfrom$_REQUEST(query string and body) and does not require the real request method to bePOST. With this option on, a link such ashttps://example.com/articles/42?_method=DELETEis routed asDELETE, and a logged-in user who follows it (a top-level navigation sendsSameSite=Laxcookies) triggers the handler. That is why the token above is required for every state-changing route, and why it must come from the request body.Leave
variable_methodoff (the default) for JSON APIs and any app that does not submit HTML forms.
By default, a handler parameter type-hinted with your request/response class
receives the shared instance. Set this to true to inject a newly
constructed instance instead. See Dependency Injection.
A PSR-11 ContainerInterface. When set,
controllers and class-typed handler dependencies are resolved through it. See
Dependency Injection.
Caches the compiled route table to a file. See Caching.
Next: Routing.
initphp/router · MIT License · part of the InitPHP family
Source · Issues · Discussions · Packagist · Contributing · Security Policy
Getting Started
Defining Routes
Handling Requests
- Dependency Injection
- Middleware
- Static File Links
- Error Handling
- Caching
- Health Checks
- Readiness Linter
Reference
Migration