带有闭包和名称的 Laravel 路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28322829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:49:47  来源:igfitidea点击:

Laravel routing with Closures and Names

phplaravelclosures

提问by Lisa

I'm curious, because I can't find much in the way of documentation on this - How would I name a route if I also want to call a closure?

我很好奇,因为我找不到太多关于此的文档 - 如果我还想调用闭包,我将如何命名路由?

I've found how I can call a controller function, but not how to name the route.

我找到了如何调用控制器函数,但没有找到如何命名路由。

Named Route:

命名路线:

Route::get( '{foo}', ['as' => 'foo.home', 'uses' => 'FooController@home'] );

Route::get( '{foo}', ['as' => 'foo.home', 'uses' => 'FooController@home'] );

Closure Route w/ controller call:

带有控制器调用的关闭路由:

Route::get( '{foo}', function() {
    $fooController = $app->make('FooController');
    return $fooController->callAction('home', $parameters = array());
});

But I can't find how to incorporate the name of the route into the second example.

但是我找不到如何将路线名称合并到第二个示例中。

回答by lukasgeiter

You can use an array with nameand usesas well:

您也可以将数组与name和一起使用uses

Route::get('{foo}', array('name' => 'foo.home', 'uses' => function(){
    $fooController = $app->make('FooController');
    return $fooController->callAction('home', $parameters = array());
}));

It also works without uses(Laravel recognizes the type Closure)

它也可以在没有uses(Laravel 识别类型Closure)的情况下工作

Route::get('{foo}', array('name' => 'foo.home', function(){
    $fooController = $app->make('FooController');
    return $fooController->callAction('home', $parameters = array());
}));

回答by Mohsen

Easiest way is call it as class

最简单的方法是将其称为类

Route::get( '{foo}', function() {
  return (new $fooController)->homeMethod($parameters);
})->name('foohome');;