萬盛學電腦網

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

PHP 反射 實戰應用:獲取類/函數定義位置、自動註冊路由、依賴注入容器原理

PHP 反射 API (ReflectionClass, ReflectionMethod, ReflectionFunction, ReflectionParameter) 讓代碼能在運行時檢查、修改自身結構。本文通過三個實戰場景——**定位定義位置、自動路由掃描、簡易依賴注入容器**——深度講解反射核心用法與性能考量。

反射核心類速查

類用途常用方法
ReflectionClass類/接口/Trait 信息getName(), getFileName(), getStartLine(), getMethods(), getProperties(), getConstructor(), newInstanceArgs(), getAttributes() (PHP 8)
ReflectionMethod方法信息getName(), getParameters(), getReturnType(), isPublic(), invoke(), invokeArgs()
ReflectionFunction函數/閉包信息getParameters(), getReturnType(), invoke(), invokeArgs()
ReflectionParameter參數信息getName(), getType(), isOptional(), getDefaultValue(), getAttributes()
ReflectionProperty屬性信息getName(), getType(), getValue($obj), setValue($obj, $val), setAccessible(true)
ReflectionAttributePHP 8 屬性 (註解)getName(), getArguments(), newInstance()

場景一:獲取類/函數定義位置 (調試/開發工具)

<?php
function getDefinitionPosition(string $name): array
{
    $info = [];

    // 1. 檢查類
    if (class_exists($name) || interface_exists($name) || trait_exists($name)) {
        $rc = new ReflectionClass($name);
        $info['class'] = [
            'file' => $rc->getFileName(),
            'start_line' => $rc->getStartLine(),
            'end_line' => $rc->getEndLine(),
            'namespace' => $rc->getNamespaceName(),
            'modifiers' => Reflection::getModifierNames($rc->getModifiers()),
        ];
    }

    // 2. 檢查函數
    if (function_exists($name)) {
        $rf = new ReflectionFunction($name);
        $info['function'] = [
            'file' => $rf->getFileName(),
            'start_line' => $rf->getStartLine(),
            'end_line' => $rf->getEndLine(),
            'namespace' => $rf->getNamespaceName(),
            'parameters' => array_map(fn($p) => [
                'name' => $p->getName(),
                'type' => $p->getType()?->getName(),
                'optional' => $p->isOptional(),
                'default' => $p->isOptional() ? $p->getDefaultValue() : null,
            ], $rf->getParameters()),
        ];
    }

    return $info;
}

// 使用
print_r(getDefinitionPosition('App\\Controller\\UserController'));
print_r(getDefinitionPosition('helper_function'));

場景二:基於註解/屬性的自動路由掃描

掃描控制器目錄,讀取方法上的 #[Route] 屬性 (PHP 8) 或 DocBlock 註解 (PHP 7),自動構建路由表。

PHP 8 屬性版 (現代標準)

<?php
#[\Attribute(Attribute::TARGET_METHOD)]
class Route
{
    public function __construct(
        public string $path,
        public array $methods = ['GET'],
        public string $name = '',
        public array $middleware = [],
    ) {}
}

// 控制器示例
class UserController
{
    #[Route('/users', methods: ['GET'], name: 'users.index')]
    public function index() { /* ... */ }

    #[Route('/users/{id}', methods: ['GET'], name: 'users.show')]
    public function show(int $id) { /* ... */ }

    #[Route('/users', methods: ['POST'], name: 'users.store', middleware: ['auth', 'throttle'])]
    public function store(Request $request) { /* ... */ }
}

// 路由掃描器
class RouteScanner
{
    public function scan(string $controllerDir, string $namespace): array
    {
        $routes = [];
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($controllerDir, FilesystemIterator::SKIP_DOTS)
        );

        foreach ($files as $file) {
            if ($file->getExtension() !== 'php') continue;

            $className = $namespace . '\\' . str_replace(['/', '.php'], ['\\', ''], 
                substr($file->getPathname(), strlen($controllerDir) + 1));

            if (!class_exists($className)) continue;

            $rc = new ReflectionClass($className);
            if ($rc->isAbstract() || !$rc->isInstantiable()) continue;

            foreach ($rc->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                $attrs = $method->getAttributes(Route::class);
                foreach ($attrs as $attr) {
                    /** @var Route $route */
                    $route = $attr->newInstance();
                    $routes[] = [
                        'path' => $route->path,
                        'methods' => $route->methods,
                        'handler' => [$className, $method->getName()],
                        'name' => $route->name ?: $method->getName(),
                        'middleware' => $route->middleware,
                        'parameters' => $this->getMethodParameters($method),
                    ];
                }
            }
        }
        return $routes;
    }

    private function getMethodParameters(ReflectionMethod $method): array
    {
        $params = [];
        foreach ($method->getParameters() as $param) {
            $params[] = [
                'name' => $param->getName(),
                'type' => $param->getType()?->getName(),
                'optional' => $param->isOptional(),
                'default' => $param->isOptional() ? $param->getDefaultValue() : null,
            ];
        }
        return $params;
    }
}

// 使用
$scanner = new RouteScanner();
$routes = $scanner->scan(__DIR__ . '/../Controller', 'App\\Controller');
// 註冊到路由器...

PHP 7 DocBlock 註解版 (兼容)


/**
 * @Route("/users", methods={"GET"}, name="users.index")
 */
public function index() { }

// 解析
$docComment = $method->getDocComment();
if (preg_match('/@Route\s*\((.*?)\)/s', $docComment, $matches)) {
    // 解析參數字符串... (建議用 doctrine/annotations 庫)
}

場景三:簡易依賴注入容器 (構造函數自動注入)

核心原理:反射構造函數參數 → 遞歸解析依賴 → 實例化注入。

<?php
class Container
{
    private array $bindings = [];      // 類名 -> 實例/工廠/單例
    private array $singletons = [];    // 單例實例緩存
    private array $resolving = [];     // 循環依賴檢測

    /** 綁定接口到實現 */
    public function bind(string $abstract, $concrete = null, bool $singleton = false): void
    {
        $this->bindings[$abstract] = ['concrete' => $concrete ?? $abstract, 'singleton' => $singleton];
    }

    /** 綁定單例 */
    public function singleton(string $abstract, $concrete = null): void
    {
        $this->bind($abstract, $concrete, true);
    }

    /** 實例化 */
    public function make(string $abstract, array $parameters = [])
    {
        // 1. 檢查單例緩存
        if (isset($this->singletons[$abstract])) {
            return $this->singletons[$abstract];
        }

        // 2. 循環依賴檢測
        if (isset($this->resolving[$abstract])) {
            throw new \RuntimeException("Circular dependency detected for {$abstract}");
        }
        $this->resolving[$abstract] = true;

        // 3. 獲取具體類
        $binding = $this->bindings[$abstract] ?? ['concrete' => $abstract, 'singleton' => false];
        $concrete = $binding['concrete'];

        // 4. 如果是閉包工廠
        if ($concrete instanceof \Closure) {
            $instance = $concrete($this, $parameters);
        } else {
            // 5. 反射構造函數自動注入
            $instance = $this->resolveClass($concrete, $parameters);
        }

        // 6. 單例緩存
        if ($binding['singleton']) {
            $this->singletons[$abstract] = $instance;
        }

        unset($this->resolving[$abstract]);
        return $instance;
    }

    private function resolveClass(string $class, array $parameters = [])
    {
        $rc = new ReflectionClass($class);
        if (!$rc->isInstantiable()) {
            throw new \RuntimeException("Class {$class} not instantiable");
        }

        $constructor = $rc->getConstructor();
        if (!$constructor) {
            return new $class();
        }

        $deps = [];
        foreach ($constructor->getParameters() as $param) {
            $name = $param->getName();
            // 顯式傳參優先
            if (array_key_exists($name, $parameters)) {
                $deps[] = $parameters[$name];
                continue;
            }

            // 類型提示自動注入
            $type = $param->getType();
            if ($type && !$type->isBuiltin()) {
                $typeName = $type->getName();
                $deps[] = $this->make($typeName);
            } elseif ($param->isOptional()) {
                $deps[] = $param->getDefaultValue();
            } else {
                throw new \RuntimeException("Cannot resolve parameter {$name} for {$class}");
            }
        }

        return $rc->newInstanceArgs($deps);
    }
}

// ========== 使用示例 ==========
$container = new Container();

// 綁定
$container->singleton(PDO::class, fn($c) => new PDO('mysql:host=127.0.0.1;dbname=app', 'user', 'pass'));
$container->bind(LoggerInterface::class, FileLogger::class);
$container->singleton(Config::class);

// 控制器自動注入
class UserController
{
    public function __construct(
        private PDO $db,
        private LoggerInterface $logger,
        private Config $config
    ) {}

    public function index() { /* ... */ }
}

// 解析控制器 (路由分發時)
$controller = $container->make(UserController::class);
$controller->index();

性能與緩存關鍵

  • 反射較慢:每次 new ReflectionClass 都解析文件。生產環境**必須緩存**反射結果(路由表、容器定義)。
  • 緩存策略: 生產環境啟動時掃描一次,序列化存 Redis/文件,請求時直接讀取緩存。
  • PHP 8 優化: ReflectionAttribute 比解析 DocBlock 快得多,強烈建議升級 PHP 8 並使用屬性。
  • 生產環境禁用開發掃描: 路由掃描、容器構建只在構建/部署階段執行,運行時只讀緩存。

總結

反射是框架級功能的基石:**路由、DI 容器、ORM 映射、序列化、驗證、測試雙工** 都依賴它。業務代碼極少直接用反射,但理解其原理能讓你深度掌握框架行為、編寫開發工具、實現動態代理/AOP。核心口訣:開發期反射掃描構建元數據 → 緩存元數據 → 運行時零反射高速執行。

copyright © 萬盛學電腦網 all rights reserved