The Router
class is a flexible and feature-rich implementation designed for managing HTTP routing in PHP applications. Below is a detailed explanation of its features and usage.
- Supports all common HTTP methods:
GET
,POST
,PUT
,PATCH
,DELETE
,OPTIONS
,HEAD
- Grouping and versioning routes
- Middleware support
- Dependency injection for route handlers
- Dynamic path parameters with regex support
- Redirect functionality
- Custom error handling (e.g., 404 errors)
- Informational output for debugging routes and errors
Add the Router
class to your project and include the necessary namespaces:
use SosoRicsi\Http\Router;
use SosoRicsi\Http\Request;
use SosoRicsi\Http\Response;
Define routes using the provided methods:
$router = new Router();
$router->get('/home', function () {
echo 'Welcome to the homepage!';
});
$router->post('/submit', function (Request $request) {
echo 'Form submitted';
});
Group related routes with a common prefix and middleware:
$router->group('/admin', function (Router $router) {
$router->get('/dashboard', function () {
echo 'Admin Dashboard';
});
}, [AdminMiddleware::class]);
Define API versions easily:
$router->version(function (Router $router) {
$router->get('/users', function () {
echo 'List of users';
});
}, [], '/api/v1');
Apply middleware to routes:
$router->get('/profile', function () {
echo 'User profile';
}, [AuthMiddleware::class]);
Redirect one route to another:
$router->redirect('/old-route', '/new-route');
Define custom error handlers:
$router->errors([
[
'error' => '404',
'handler' => function () {
echo 'Custom 404 Page Not Found';
}
]
]);
Execute the router based on the current request:
$router->run();
Alternatively, specify the URI and method manually:
$router->run('/test', 'GET');
Use curly braces for dynamic parameters, optionally with regex:
$router->get('/user/{id:\d+}', function ($id) {
echo "User ID: $id";
});
Automatically inject dependencies into route handlers:
$router->get('/inject', function (Request $request, Response $response) {
$response->setBody('Injected dependencies!');
});
View routes and error handlers for debugging:
$router->info(true, true);
Defines a GET route.
Defines a POST route.
Defines a PUT route.
Defines a PATCH route.
Defines a DELETE route.
Defines an OPTIONS route.
Redirects a route to another location.
Groups related routes with a prefix and middleware.
Defines a versioned route group.
Adds custom error handlers.
Processes the current request.
Displays debugging information about routes and error handlers.
$router = new Router();
$router->get('/', function () {
echo 'Welcome!';
});
$router->group('/api', function (Router $router) {
$router->get('/users', function () {
echo 'List of users';
});
});
$router->run();