Car*_*cce 5 php attributes php-8
假设我有以下属性声明
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Route
{
public function __construct(
public string $path,
public ?string $method = null,
public ?string $alias = null
)
{}
}
Run Code Online (Sandbox Code Playgroud)
我在一些控制器方法中使用它,如下所示:
class Controller
{
#[Route('/index/')]
#[Route('/home/', alias: 'home')]
public function index()
{
...
}
#[Route('/create/', 'POST')]
public function create(Request $request)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
我如何获取这些属性实例并读取它的属性?
您可以使用本机 php反射 api来完成此操作。
首先,您必须检索所需的方法反射。在下面的示例中,我将检索所有公共方法:
$reflectionClass = new ReflectionClass(Controller::class);
$methods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC);
Run Code Online (Sandbox Code Playgroud)
这将返回一个包含所有公共方法反射的数组。
然后,要读取它并检索这些Route实例,只需循环它并使用“newInstance()”属性反射方法即可。就像这样:
foreach ($methods as $method) {
$attributes = $method->getAttributes(Route::class);
echo "reflecting method '", $method->getName(), "'\r\n";
foreach ($attributes as $attribute) {
var_dump($attribute->newInstance());
}
}
Run Code Online (Sandbox Code Playgroud)
这将输出:
reflecting method 'index'
object(Route)#8 (3) {
["path"]=>
string(7) "/index/"
["method"]=>
NULL
["alias"]=>
NULL
}
object(Route)#8 (3) {
["path"]=>
string(6) "/home/"
["method"]=>
NULL
["alias"]=>
string(4) "home"
}
reflecting method 'create'
object(Route)#7 (3) {
["path"]=>
string(8) "/create/"
["method"]=>
string(4) "POST"
["alias"]=>
NULL
}
Run Code Online (Sandbox Code Playgroud)
以下是完整工作示例的要点: https://gist.github.com/carloscarucce/fce40cb3299dd69957db001c21422b04
| 归档时间: |
|
| 查看次数: |
3801 次 |
| 最近记录: |