依赖注入和IoC容器


laravel - dependency injection and the IoC Container

我试图围绕依赖注入和IoC容器包装我的头,我使用我的UserController作为一个例子。我正在定义UserController依赖于它的构造函数,然后使用App::bind()将这些对象绑定到它。如果我使用Input::get() facade/method/thing,我没有利用我刚刚注入的Request对象吗?我应该使用下面的代码来代替,现在请求对象被注入或doesInput::get()解析到相同的请求实例?我想使用静态外观,但如果它们解析为未注入的对象则不使用。

$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');
}

如果您担心可测试性问题,那么您应该只注入没有通过facade路由的实例,因为facade本身已经是可测试的(这意味着您可以在L4中模拟它们)。您不需要注入响应、散列器、视图环境、请求等。从表面上看,你只需要注射$user

对于其他一切,我只坚持使用静态facade。在基础Facade类上检查swapshouldReceive方法。您可以很容易地用自己的模拟对象替换掉底层实例,或者简单地开始模拟,例如,View::shouldReceive()