ホームページ >バックエンド開発 >PHPチュートリアル >PHP デザイン パターン: フロント コントローラー
フロント コントローラーは、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
ホームコントローラー
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 中国語 Web サイトの他の関連記事を参照してください。