The Front Controller is a design pattern used in web application development to centralize request handling. Instead of having multiple entry points for different parts of the system, all requests are routed through a single central controller, responsible for directing them to the appropriate component or module.
/app /Controllers HomeController.php ProductController.php /Core Entrypoint.php /config routes.php /public index.php /vendor composer.json
To implement PSR-4, create a composer.json file in the project root:
{ "autoload": { "psr-4": { "App\": "app/" } } }
Run the following command to generate the autoloader:
composer dump-autoload
apache(.htaccess)
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [L]
nginx
server { listen 80; server_name example.com; root /path/to/your/project/public; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # Adjust for your PHP version fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~* \.(css|js|jpg|jpeg|png|gif|ico|woff|woff2|ttf|svg|eot|ttc|otf|webp|avif)$ { expires max; log_not_found off; } location ~ /\.ht { deny all; } }
After saving the configuration file, restart Nginx to apply the changes
sudo systemctl reload nginx
HomeController
namespace App\Controllers; class HomeController { public function index(): void { echo "Welcome to the home page!"; } }
ProductController
namespace App\Controllers; class ProductController { public function list(): void { echo "Product list."; } }
Entrypoint
namespace App\Core; class Entrypoint { public function __construct(private array $routes) { } public function handleRequest(): void { $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); if (isset($this->routes[$uri])) { $route = $this->routes[$uri]; $controller = new $route['controller']; $method = $route['method']; if (method_exists($controller, $method)) { $controller->$method(); } else { $this->sendResponse(500, "Method not found."); } } else { $this->sendResponse(404, "Page not found."); } } private function sendResponse(int $statusCode, string $message): void { http_response_code($statusCode); echo $message; } }
routes
$routes = [ '/' => [ 'controller' => 'HomeController', 'method' => 'index' ], '/products' => [ 'controller' => 'ProductController', 'method' => 'list' ] ];
require_once __DIR__ . '/../vendor/autoload.php'; use App\Core\Entrypoint; $routes = require __DIR__ . '/../config/routes.php'; $entrypoint = new Entrypoint($routes); $entrypoint->handleRequest();
This implementation:
The above is the detailed content of PHP Design Patterns: Front Controller. For more information, please follow other related articles on the PHP Chinese website!