How can the Front-Controller-Pattern be implemented in PHP to manage page routing and content display?
The Front-Controller-Pattern can be implemented in PHP by creating a central controller that handles all incoming requests, routes them to the appropriate page controller, and displays the content accordingly. This helps in centralizing the request handling logic and improving the maintainability of the codebase.
// index.php
// Central controller
class FrontController {
public function handleRequest($request) {
switch($request) {
case 'home':
$controller = new HomeController();
break;
case 'about':
$controller = new AboutController();
break;
default:
$controller = new ErrorController();
}
$controller->display();
}
}
// Page controllers
class HomeController {
public function display() {
echo 'Home Page Content';
}
}
class AboutController {
public function display() {
echo 'About Page Content';
}
}
class ErrorController {
public function display() {
echo 'Error: Page not found';
}
}
// Usage
$frontController = new FrontController();
$request = $_GET['page'] ?? 'home';
$frontController->handleRequest($request);