萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

ThinkPHP 控制器調度機制深度解析:反射類實現前置/後置操作與參數綁定

核心概念

ThinkPHP 控制器調度器利用 PHP 內建的 ReflectionClass 與 ReflectionMethod 實現:

  1. 自動偵測並執行 _before_動作名、_after_動作名 前置/後置方法。
  2. 依據 URL 參數自動綁定動作方法的參數(支援預設值)。
  3. 權限檢查(僅執行 public 方法)。

關鍵反射類方法速查

類別方法用途
ReflectionClasshasMethod(string)檢查方法是否存在
getMethod(string)取得方法反射物件
ReflectionMethodisPublic()檢查是否為 public
getNumberOfParameters()取得參數總數
getParameters()取得所有參數反射物件陣列
ReflectionParametergetName() / isDefaultValueAvailable() / getDefaultValue()參數名、是否有預設值、預設值

完整調度邏輯演示程式碼

<?php
class IndexAction {
    public function index() {
        echo 'index' . PHP_EOL;
    }
    
    public function test($year = 2012, $month = 2, $day = 21) {
        echo $year . '--------' . $month . '-----------' . $day . PHP_EOL;
    }
    
    public function _before_index() {
        echo __FUNCTION__ . PHP_EOL;
    }
    
    public function _after_index() {
        echo __FUNCTION__ . PHP_EOL;
    }
}

// --- 調度器核心邏輯 ---

// 1. 執行無參數的 index 方法(含前置/後置)
$method = new ReflectionMethod('IndexAction', 'index');
if ($method->isPublic()) {
    $class = new ReflectionClass('IndexAction');
    
    // 執行前置方法 _before_index
    if ($class->hasMethod('_before_index')) {
        $beforeMethod = $class->getMethod('_before_index');
        if ($beforeMethod->isPublic()) {
            $beforeMethod->invoke(new IndexAction);
        }
    }
    
    // 執行主方法
    $method->invoke(new IndexAction);
    
    // 執行後置方法 _after_index
    if ($class->hasMethod('_after_index')) {
        $afterMethod = $class->getMethod('_after_index');
        if ($afterMethod->isPublic()) {
            $afterMethod->invoke(new IndexAction);
        }
    }
}

// 2. 執行帶參數的 test 方法(自動綁定 $_REQUEST 參數)
$method = new ReflectionMethod('IndexAction', 'test');
$params = $method->getParameters();
$args = [];

foreach ($params as $param) {
    $paramName = $param->getName();
    if (isset($_REQUEST[$paramName])) {
        $args[] = $_REQUEST[$paramName]; // 從請求取得
    } elseif ($param->isDefaultValueAvailable()) {
        $args[] = $param->getDefaultValue(); // 使用預設值
    }
}

// 參數數量匹配才執行
if (count($args) === $method->getNumberOfParameters()) {
    $method->invokeArgs(new IndexAction, $args);
} else {
    echo 'parameters is not match!';
}
?>

執行結果預期

_before_index
index
_after_index
2012--------2-----------21  // 若無 $_REQUEST 參數,使用預設值

實務應用建議

  • 前置方法常用於:權限驗證、資料預處理、日誌記錄。
  • 後置方法常用於:資料清理、回應格式化、效能統計。
  • 參數自動綁定讓動作方法簽名更乾淨,減少 $_GET/$_POST 直接存取。
  • 現代框架(Laravel、ThinkPHP 5+)改用中介層與依賴注入,但反射原理相通。
copyright © 萬盛學電腦網 all rights reserved