前端控制器是Web应用程序开发中用于集中请求处理的设计模式。所有请求都通过单个中央控制器路由,负责将它们定向到适当的组件或模块,而不是为系统的不同部分设置多个入口点。
/app /Controllers HomeController.php ProductController.php /Core Entrypoint.php /config routes.php /public index.php /vendor composer.json
要实现PSR-4,请在项目根目录中创建一个composer.json文件:
{ "autoload": { "psr-4": { "App\": "app/" } } }
运行以下命令来生成自动加载器:
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; } }
保存配置文件后,重新启动 Nginx 以应用更改
sudo systemctl reload nginx
HomeController
namespace App\Controllers; class HomeController { public function index(): void { echo "Welcome to the home page!"; } }
产品控制器
namespace App\Controllers; class ProductController { public function list(): void { echo "Product list."; } }
入口点
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 = [ '/' => [ '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();
此实现:
以上是PHP 设计模式:前端控制器的详细内容。更多信息请关注PHP中文网其他相关文章!