如何从PHP 8属性(反射)中获取方法名



我正在开发一个小型PHP框架(用于学习)。它有一个LoginController类的文件,其中包含一个带有Route属性的方法(下面的代码)。是否有任何方法获得方法的名称在路由属性类使用反射?

类的方法使用属性:

class LoginController {
#[Route('GET', '/login')]
public function index() {
// some code
}
}

"Route"属性类:

use Attribute;
use ReflectionMethod;
#[Attribute]
class Route {
public function __construct($method, $routeUri) {
// Can I get the method name ("index") from attribute instead of writing it?
// And the class name?
$reflection = new ReflectionMethod(AppControllersLoginController::class, 'index');
$closure = $reflection->getClosure();
// Register a route...
Router::add($method, $routeUri, $closure);
}
}

反射是一个选项,但请注意,您将循环遍历类中所有方法的所有属性(至少直到找到匹配的方法)。当然,如果所有的路由都需要注册,这也没有那么糟糕。

$classRef = new ReflectionClass(LoginController::class);
foreach ($classRef->getMethods() as $method) {
$methodRef = new ReflectionMethod($method->class, $method->name);
foreach ($methodRef->getAttributes() as $attribute) {
if (
$attribute->getName() === 'Route' 
&& $attribute->getArguments() === [$method, $routeUri]
) {
// you can register your route here
}
}
}

就类而言,最简单的方法就是用所有控制器类名创建一个数组。有些包可以检测给定命名空间中的所有类,它们可以用于自动检测控制器。

最新更新