Router
The Router
class is responsible for defining and managing the routes in your application. It maps HTTP requests to specific controller actions, allowing you to organize and handle different endpoints in a structured manner. Below is an explanation of each method in the class.
Find out how to use Route
Class Definition and Properties
<?php
namespace System\Core;
class Router {
protected $routes = [];
$routes
: An array that holds the list of defined routes.
get()
get()
<?php
public function get($pattern, $callback, $middleware = []) {
$this->addRoute('GET', $pattern, $callback, $middleware);
}
Defines a route that responds to GET requests.
$pattern
: The URL pattern for the route.$callback
: The controller action or callback to handle the request.$middleware
: An array of middleware to apply to the route.
Calls the addRoute
method to add the route to the $routes
array with the HTTP method set to 'GET'.
post()
post()
<?php
public function post($pattern, $callback, $middleware = []) {
$this->addRoute('POST', $pattern, $callback, $middleware);
}
Defines a route that responds to POST requests.
$pattern
: The URL pattern for the route.$callback
: The controller action or callback to handle the request.$middleware
: An array of middleware to apply to the route.
put()
put()
<?php
public function put($uri, $controller, $middleware = []) {
$this->addRoute('PUT', $uri, $controller, $middleware);
}
Defines a route that responds to PUT requests.
$uri
: The URL pattern for the route.$controller
: The controller action or callback to handle the request.$middleware
: An array of middleware to apply to the route
delete()
delete()
<?php
public function delete($uri, $controller, $middleware = []) {
$this->addRoute('DELETE', $uri, $controller, $middleware);
}
Defines a route that responds to DELETE requests.
$uri
: The URL pattern for the route.$controller
: The controller action or callback to handle the request.$middleware
: An array of middleware to apply to the route.
match()
match()
<?php
public function match($uri, $method) {}
Matches the given URI with the defined routes and returns the controller, action, parameters, and middleware.
$uri
: The URI to match.$method
: The HTTP method of the request.
Conclusion
The Router
class provides a robust framework for defining and managing routes in your application. By mapping HTTP requests to specific controller actions and integrating middleware, it ensures that your application can handle requests in a structured and secure manner. This class makes it easy to organize and extend your application, supporting various HTTP methods, dynamic routing, and middleware integration.
Find out how to use Route
Last updated
Was this helpful?