What are some best practices for designing and implementing a flexible and efficient routing system in PHP applications?
Designing and implementing a flexible and efficient routing system in PHP applications involves creating a centralized routing mechanism that maps URLs to specific controllers and actions. This can be achieved by using a router class that parses the incoming request URI and directs it to the appropriate controller and action based on predefined routes. Additionally, using regular expressions to define dynamic routes can make the routing system more flexible and powerful.
// Define a Router class to handle routing
class Router {
private $routes = [];
// Add a new route to the router
public function addRoute($pattern, $controller, $action) {
$this->routes[$pattern] = ['controller' => $controller, 'action' => $action];
}
// Dispatch the request to the appropriate controller and action
public function dispatch($uri) {
foreach ($this->routes as $pattern => $route) {
if (preg_match($pattern, $uri, $matches)) {
$controller = $route['controller'];
$action = $route['action'];
// Instantiate the controller and call the action method
$controllerInstance = new $controller();
$controllerInstance->$action($matches);
return;
}
}
// Handle 404 Not Found
http_response_code(404);
echo '404 Not Found';
}
}
// Example usage
$router = new Router();
$router->addRoute('/^\/users\/(\d+)$/', 'UserController', 'show');
$router->dispatch($_SERVER['REQUEST_URI']);