What role does a router play in handling URLs in PHP frameworks?

In PHP frameworks, a router plays a crucial role in handling URLs by mapping incoming requests to the appropriate controller and method. It helps in defining routes and their corresponding actions, allowing for clean and organized URL structures. By using a router, developers can easily manage and navigate different pages and functionalities within the application.

// Example of implementing a router in a PHP framework

// Define routes
$routes = [
    '/' => 'HomeController@index',
    '/about' => 'AboutController@index',
    '/contact' => 'ContactController@index'
];

// Get current URL
$currentUrl = $_SERVER['REQUEST_URI'];

// Match the URL to a route
if(array_key_exists($currentUrl, $routes)) {
    list($controller, $method) = explode('@', $routes[$currentUrl]);
    $controllerInstance = new $controller();
    $controllerInstance->$method();
} else {
    echo '404 - Page not found';
}