Laravel:依赖注入与门面? [英] Laravel : Dependency injection vs Facades?
问题描述
我以前一直在做的事情是仅使用构造函数注入我的模型,并且使用Facades作为Laravel提供的类,即Session
,Auth
,例如,Validator
等.如果我通过构造注入每个类(我的或Laravel的)并通过$this->..
语法使用它,或者我应该使用构造函数注入我自己的类,将是一个好主意吗? strong>并使用Laravel提供的任何东西使用Facades?
What, I had been doing previously was to inject only MY MODELS using the constructor and use Facades for the Laravel's provided classes i.e. Session
, Auth
, Validator
etc, for example. Will it be a good idea if I inject each and every class (either mine or Laravel's) through construct and use it by $this->..
syntax or should I inject my own classes using constructor and use Facades for anything provided by Laravel?
更具体地说,这是我的控制器通常的外观:
To be more specific, here is what my controllers normally look like:
class MyController extends BaseController
{
public function __construct( User $user, Bookmark $bookmark ) {
$this->user = $user;
$this->bookmark = $bookmark
}
public function foobar ( ) {
$user_id = Input::get('bar');
...
Session::get('someInfo');
...
return Redirect::to('/');
}
...
}
我应该像下面那样构造控制器之类的方法吗?
Should I structure my methods like controller like following, instead?
class MyController extends BaseController
{
public function __construct( User $user, Bookmark $bookmark, Input $input, Session $session, Redirect $redirect ) {
$this->user = $user;
$this->bookmark = $bookmark
$this->input = $input;
$this->session = $session;
$this->redirect = $redirect;
}
public function foobar ( ) {
$user_id = $this->input->get('bar');
...
$this->session->get('someInfo');
...
return $this->redirect->to('/');
}
...
}
推荐答案
Laravel现在为与路由相关的类方法(不仅是构造方法)支持相同的注入功能,例如控制器和中间件.
Laravel now supports the same injection functionality for methods of classes (not just constructors) that are route-related, such as controllers and middleware.
您可以通过仅注入依赖项唯一的方法来防止不必要的注入,也许在构造函数中保留更常见的依赖项:
You could prevent unnecessary injections by only injecting to methods where the dependency is unique, perhaps leaving more common dependencies in the constructor:
class MyController extends BaseController
{
public function __construct( Input $input, Session $session, Redirect $redirect ) {
$this->input = $input;
$this->session = $session;
$this->redirect = $redirect;
}
public function foobar ( User $user, Bookmark $bookmark ) {
$user_id = $this->input->get('bar');
...
$this->session->get('someInfo');
...
return $this->redirect->to('/');
}
...
}
关于您是否应该以这种方式进行操作,这取决于您-强制所有依赖项出现在方法定义中对我来说似乎更干净,并且更易于进行单元测试.
As for whether you should do it this way, that's up to you - forcing all dependencies to appear in method definitions seems cleaner to me, and easier to unit test.
这篇关于Laravel:依赖注入与门面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!