[英]How can I use a Laravel closure to call a controller's __invoke() method?
In my Laravel application I have created a controller named InvokableController. 在我的Laravel应用程序中,我创建了一个名为InvokableController的控制器。 It contains this function:
它包含以下功能:
public function __invoke()
{
return view('home');
}
I'd like to be able to call the __invoke method, like this: 我希望能够调用__invoke方法,如下所示:
Route::get('/', function () {
$invokableObj = new InvokableController();
$invokableObj();
})->name('home');
While this works: 尽管这可行:
Route::get('/', 'InvokableController')->name('home');
It's not what I'm looking for. 这不是我要找的东西。 I'd like to call the invoke method in this manner:
我想以这种方式调用invoke方法:
$invokableObj = new InvokableController();
$invokableObj();
I tried with and without the parentheses after InvokableController
, on the line that assigns $invokableObj
, with no luck. 我尝试在分配
$invokableObj
的行上在InvokableController
之后加上或不加上括号,但没有运气。
I don't get any error messages. 我没有收到任何错误消息。 I tried returning something else at the bottom of the closure, like the number 1, and it renders 1 in the browser, so I know we're getting through the previous lines of code.
我尝试在闭包的底部返回其他内容,例如数字1,它在浏览器中呈现1,所以我知道我们已经遍历了前面的代码行。
APP_DEBUG
is true
. APP_DEBUG
为true
。 Other error messages are rendered where I mess up. 其他错误消息在我搞砸的地方呈现。 Does that make this some type of logical error?
这是否会导致某种逻辑错误?
Its just a class, so $invokableObj->__invoke()
should work just fine. 它只是一个类,所以
$invokableObj->__invoke()
应该可以正常工作。 Or you can use laravel DI: 或者您可以使用laravel DI:
app()->call(InvokableController::class . '@__invoke');
Route::get('/', function () {
return app()->call(InvokableController::class . '@__invoke');
// or
$invokableObj = new InvokableController();
return $invokableObj->__invoke();
})->name('home');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.