ThinkPHP 控制器調度器利用 PHP 內建的 ReflectionClass 與 ReflectionMethod 實現:
_before_動作名、_after_動作名 前置/後置方法。| 類別 | 方法 | 用途 |
|---|---|---|
ReflectionClass | hasMethod(string) | 檢查方法是否存在 |
getMethod(string) | 取得方法反射物件 | |
ReflectionMethod | isPublic() | 檢查是否為 public |
getNumberOfParameters() | 取得參數總數 | |
getParameters() | 取得所有參數反射物件陣列 | |
ReflectionParameter | getName() / 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 直接存取。