前端控制器是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中文網其他相關文章!