Tor*_*eer 13 php controller laravel laravel-5
在Laravel Controller中,如果所有函数都使用Request,那么直接在构造函数而不是函数中注入Request是正确的吗?
下面的代码有效,我只是想知道它是否正确,是否有副作用......
class BananaController extends Controller
{
protected $request; // request as an attribute of the controllers
public function __construct(Request $request)
{
$this->middleware('auth');
$this->request = $request; // Request becomes available for all the controller functions that call $this->request
}
public function store()
{
$this->validate($this->request, [
'text' => 'required',
]);
// I save the banana attributes and the controller continues...
Run Code Online (Sandbox Code Playgroud)
对我来说很容易,有关stackoverflow的第一个问题:-)
[ADDENDUM]要明确的是,"常规"代码将是:
class BananaController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, [
'text' => 'required',
]);
// I save the banana attributes and the controller continues...
Run Code Online (Sandbox Code Playgroud)
我一直在使用相同的技术来保护我所有的资源控制器路由请求(例如检查登录用户是否有权访问此资源)
然而,从 Laravel 5.3 开始,控制器构造函数现在在中间件执行之前运行,它实际上破坏了请求中的路由模型绑定。
因此,如果您将请求直接注入到控制器方法中,就像在 Laravel 文档中一样,并且如果您将任何模型绑定到您的路由,它会很好地解决它,但是如果您在控制器构造函数中注入您的请求并尝试访问您的模型像下面这样的请求 - 它只会返回资源 ID 而不是模型。
//Route service provider
Route::model('resource', MyModel::class);
//Request class
public function authorize()
{
//We expect to get a resource or null
//But now it just returns the resource id
if (!is_null($this->resource))
{
return $this->resource->createdBy->id == $this->getLoggedUser()->id;
}
}
Run Code Online (Sandbox Code Playgroud)
如果控制器中的所有或几乎所有方法BananaController
都使用该类Request
,则注入依赖项的最常见方法是通过类的构造函数,如示例中所示。
使用构造函数注入有几个优点:
如果依赖项是必需的,并且类没有它就无法工作,那么通过构造函数注入它可以确保在使用该类时它存在,因为没有它就无法构造该类。
构造函数仅在创建对象时调用一次,因此您可以确保依赖关系在对象的生命周期内不会更改。
请注意,这些优点确实意味着构造函数注入不适合使用可选依赖项。与类层次结构结合使用也更加困难:如果一个类使用构造函数注入,那么扩展它并覆盖构造函数就会出现问题。