搜尋
首頁後端開發php教程PHP 設計模式:前端控制器

PHP Design Patterns: Front Controller

前端控制器是Web應用程式開發中用於集中請求處理的設計模式。所有請求都透過單一中央控制器路由,負責將它們定向到適當的元件或模組,而不是為系統的不同部分設定多個入口點。

它是如何運作的

  1. 單一入口點: 所有 HTTP 請求都使用 Web 伺服器設定(例如,Apache 的 .htaccess 或 Nginx 中的路由規則)重定向到單一檔案(通常為 index.php)。
  2. 路由:前端控制器分析 URL 並決定應該執行哪一部分程式碼。這可以手動實現或使用路由庫/框架來實現。
  3. 委託:根據路由,前端控制器將請求委託給適當的控制器(類別或方法),該控制器處理資料並回傳回應。
  4. 回應: 控制器產生一個回應(通常是 HTML 或 JSON),發送回瀏覽器或用戶端。

優點

  • 集中化:所有傳入的應用程式流都透過單點處理,從而更輕鬆地管理和追蹤請求。
  • 靈活性:輕鬆整合全域功能,如驗證、權限控制、日誌或錯誤處理。
  • 復用性:通用邏輯可以集中在前端控制器中,減少重複。
  • 可維護性:集中化簡化了更新,例如新增新的路由或控制器。

例子

目錄結構

/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();

結果

此實作:

  • 使用前端控制器模式集中請求處理。
  • 將路由邏輯封裝在 Entrypoint 類別中。
  • 採用 PSR-4 進行自動載入和更好的程式碼組織。
  • 使用 Nginx 設定進行無縫設定。

以上是PHP 設計模式:前端控制器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
優化PHP代碼:減少內存使用和執行時間優化PHP代碼:減少內存使用和執行時間May 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP電子郵件:分步發送指南PHP電子郵件:分步發送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

如何通過PHP發送電子郵件:示例和代碼如何通過PHP發送電子郵件:示例和代碼May 09, 2025 am 12:13 AM

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

高級PHP電子郵件:自定義標題和功能高級PHP電子郵件:自定義標題和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送電子郵件的指南使用PHP和SMTP發送電子郵件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

使用PHP發送電子郵件的最佳方法是什麼?使用PHP發送電子郵件的最佳方法是什麼?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依賴注入的最佳實踐PHP中依賴注入的最佳實踐May 08, 2025 am 12:21 AM

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

PHP性能調整技巧和技巧PHP性能調整技巧和技巧May 08, 2025 am 12:20 AM

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。