是否可以将路由参数传递给 Laravel 中的控制器构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25766894/
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
Is it possible to pass a route parameter to controller constructor in Laravel?
提问by chmoelders
Is it possible to inject a route-paramter (or an route segment) to the controller-constructor?
是否可以向控制器构造函数注入路由参数(或路由段)?
You find some code to clarify my question.
你找到了一些代码来澄清我的问题。
class TestController{
protected $_param;
public function __construct($paramFromRoute)
{
$this->param = $paramFromRoute;
}
public function testAction()
{
return "Hello ".$this->_param;
}
}
----------------------------------------------------
App::bind('TestController', function($app, $paramFromRoute){
$controller = new TestController($paramFromRoute);
return $controller;
});
----------------------------------------------------
// here should be some magic
Route::get('foo/{bar}', 'TestController');
回答by Antonio Carlos Ribeiro
It's not possible to inject them, but you have access to all of them via:
不可能注入它们,但您可以通过以下方式访问所有它们:
class TestController{
protected $_param;
public function __construct()
{
$id = Route::current()->getParameter('id');
}
}
回答by Erusso87
Laravel 5.3.28
Laravel 5.3.28
You can't inject the parameter... But, you can inject the request and get it from the router instance, like this:
您不能注入参数...但是,您可以注入请求并从路由器实例中获取它,如下所示:
//route: url_to_controller/{param}
public function __construct(Request $request)
{
$this->param = $request->route()->parameter('param');
}
回答by Gabriel Stafoca
In Laravel 5.4, you can use this to request the parameter:
在Laravel 5.4 中,您可以使用它来请求参数:
public function __construct(Request $request) {
$id = $request->get("id");
}
回答by simon
Lastly, but most importantly, you may simply "type-hint" the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, queue jobs, middleware, and more. In practice, this is how most of your objects are resolved by the container.
最后,但最重要的是,您可以简单地在由容器解析的类的构造函数中“类型提示”依赖项,包括控制器、事件侦听器、队列作业、中间件等。实际上,这就是容器解析大多数对象的方式。