What are some best practices for implementing a PHP router?
When implementing a PHP router, it is important to follow best practices to ensure clean and maintainable code. One key practice is to define routes in a separate file or class to keep the routing logic organized and easy to manage. Additionally, using regular expressions to match routes can provide flexibility and efficiency in handling different URL patterns. It is also recommended to implement a fallback route to handle 404 errors and other unexpected requests.
// Define routes in a separate file or class
$routes = [
'/' => 'HomeController@index',
'/about' => 'AboutController@index',
'/contact' => 'ContactController@index'
];
// Match the current URL with defined routes using regular expressions
$requestUri = $_SERVER['REQUEST_URI'];
foreach ($routes as $route => $handler) {
if (preg_match('#^' . $route . '$#', $requestUri)) {
$parts = explode('@', $handler);
$controller = $parts[0];
$method = $parts[1];
// Call the controller method
$controllerInstance = new $controller();
$controllerInstance->$method();
exit;
}
}
// Fallback route for 404 errors
echo '404 Not Found';