Skip to content

Config & YAML Routes

If you prefer configuration-based routing over PHP attributes, the router supports both array and YAML registration.

$router->registerFromConfig([
['GET', '/users', UserController::class, 'index', 200],
['POST', '/users', UserController::class, 'store', 201],
['GET', '/users/{id}', UserController::class, 'show', 200],
['PUT', '/users/{id}', UserController::class, 'update', 200],
['DELETE', '/users/{id}', UserController::class, 'destroy', 204],
]);

Each entry is [method, path, controller, action, statusCode].

Requires symfony/yaml:

Terminal window
composer require symfony/yaml

routes.yaml:

routes:
- method: GET
path: /users
controller: App\Controllers\UserController
action: index
status: 200
- method: POST
path: /users
controller: App\Controllers\UserController
action: store
status: 201
$router->registerFromYaml(__DIR__ . '/../routes.yaml');

match() throws a RuntimeException when a route is not found or the method is not allowed:

try {
[$controller, $method, $params, $status] = $router->match('GET', '/not-found');
} catch (\RuntimeException $e) {
$e->getCode(); // 404 = not found, 405 = method not allowed
}