SimpleRouter is a lightweight PHP routing library that helps you define and handle HTTP routes easily. It allows you to create routes for different HTTP methods (GET, POST) and execute corresponding callbacks when a matching route is found.
You can include the SimpleRouter class in your project by copying the provided Router class file into your project directory.
- Define Routes:
Use
getandpostmethods of theRouterclass to define routes. The routes consist of a path and a callback that will be executed when the route is matched.
// Using a closure
Router::get('/info', function() {
phpinfo();
});
// Using a controller method
Router::get('/user/{name}', [Controllers\Controller::class, 'show']);
Router::post('/submit', [Controllers\Controller::class, 'submitForm']);You can use dynamic segments in the path by enclosing them in curly braces.
- Dispatch Routes:
Create a
Requestobject representing the incoming HTTP request and pass it to thedispatchmethod of theRouterto find and execute the matching route.
$request = new Request('GET', 'home/John');
$response = Router::dispatch($request);- Handle Responses:
The
dispatchmethod returns aResponseobject generated by the matched route's callback. You can then handle and manipulate the response as needed.
echo $response->getBody();MIT, see LICENSE.
PRs welcome. Please open an issue first for major changes.