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
get
andpost
methods of theRouter
class 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
Request
object representing the incoming HTTP request and pass it to thedispatch
method of theRouter
to find and execute the matching route.
$request = new Request('GET', 'home/John');
$response = Router::dispatch($request);
- Handle Responses:
The
dispatch
method returns aResponse
object generated by the matched route's callback. You can then handle and manipulate the response as needed.
echo $response->getBody();
Contributions are welcome! Feel free to submit a pull request.
This project is licensed under the MIT License - see the LICENSE file for details.