在Laravel 8中是否可以不为类中的方法指定路由,也就是说,使它们能够自动工作?
假设有一个类CreateController和方法
function doc() {...}
function pdf() {...}
function xls() {...}也就是说,当在表单site.com/create/doc的地址访问url时,它计算出类CreateController的方法doc。
或者没有这样的可能性,您必须为每个方法注册一条路由,即
Route::get('/create/doc', 'CreateController@doc');
Route::get('/create/pdf', 'CreateController@pdf');
Route::get('/create/xls', 'CreateController@xls');
...发布于 2021-06-16 12:15:09
不是直接在第二个字符串参数中,而是将此参数设置为回调函数:
Route::get('/create/{type}', function(string $type) {
return (new CreateController)->{$type}();
})->where('type', 'doc|pdf|xls');如果希望允许所有方法作为类型并保持其动态,则可以在不编辑路由的情况下从控制器中添加或删除:
$class = new ReflectionClass(CreateController::class);
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
Route::get('/create/{type}', function(string $type) {
return (new CreateController)->{$type}();
})->where('type', implode('|', $methods));https://stackoverflow.com/questions/68001129
复制相似问题