Laravel - 依赖注入和IoC容器

4

我正在尝试理解依赖注入和IoC容器,并以我的UserController为例。在构造函数中定义了UserController所依赖的内容,然后使用App::bind()将这些对象绑定到它上面。如果我使用Input::get()外观/方法/工具,我是否没有利用刚刚注入的Request对象?现在,既然已经注入了Request对象,我应该使用以下代码,还是Input::get()会解析为相同的Request实例?我想使用静态外观,但前提是它们解析为已注入的对象。

$this->request->get('email');

依赖注入
<?php
App::bind('UserController', function() {
    $controller = new UserController(
        new Response,
        App::make('request'),
        App::make('view'),
        App::make('validator'),
        App::make('hash'),
        new User
    );
    return $controller;
});

用户控制器

<?php
class UserController extends BaseController {

protected $response;
protected $request;
protected $validator;
protected $hasher;
protected $user;
protected $view;

public function __construct(
    Response $response,
    \Illuminate\Http\Request $request,
    \Illuminate\View\Environment $view,
    \Illuminate\Validation\Factory $validator,
    \Illuminate\Hashing\BcryptHasher $hasher,
    User $user
){
    $this->response = $response;
    $this->request = $request;
    $this->view = $view;
    $this->validator = $validator;
    $this->hasher = $hasher;
    $this->user = $user;
}

public function index()
{
    //should i use this?
    $email = Input::get('email');
    //or this?
    $email = $this->request->get('email');

    //should i use this?
    return $this->view->make('users.login');

    //or this?
    return View::make('users.login');
}
1个回答

10
如果您担心测试问题,那么您真正需要注入的只有那些没有通过门面路由的实例,因为这些门面本身已经是可测试的(也就是说,在L4中可以模拟这些门面)。您不需要注入响应、哈希器、视图环境、请求等内容。从外观看来,您只需要注入$user即可。
对于其他所有内容,我建议您仍然使用静态门面。请查看Facade类上的swapshouldReceive方法。您可以轻松地用自己的模拟对象替换底层实例,或者简单地开始使用例如View::shouldReceive()的模拟。
希望这可以帮助您。

2
因为使用Facade来推广以下做法,扣1分:全局状态、静态调用以实现耦合(特别是与框架的耦合),以及服务定位器来解决依赖关系,这会使你的对象API变得虚伪。 - Jimbo
1
@Jimbo,我认为你说的话揭示了我对Laravel的不安。 - Ian Lewis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接