What is the role of a router in object-oriented PHP programming for internal linking on a website?
In object-oriented PHP programming, a router is used to handle internal linking on a website by mapping URLs to specific controller methods. This allows for cleaner and more organized code structure, as well as easier maintenance and scalability of the website.
class Router {
private $routes = [];
public function addRoute($url, $controller) {
$this->routes[$url] = $controller;
}
public function route($url) {
if(array_key_exists($url, $this->routes)) {
$controller = new $this->routes[$url]();
$controller->handleRequest();
} else {
// Handle 404 error
echo "404 Page Not Found";
}
}
}
// Example of adding routes
$router = new Router();
$router->addRoute('/', 'HomeController');
$router->addRoute('/about', 'AboutController');
// Example of routing a URL
$router->route('/about');
Related Questions
- What is the recommended method to check if a table exists in a MySQL database using PHP?
- In PHP, what are the differences between using $_SESSION variables and $_REQUEST variables, and how should they be properly utilized in a web application workflow?
- What considerations should developers take into account when deciding whether to purchase and use scripts like "db_easy" in their PHP projects?