laravel - 依赖注入和IoC容器

Dav*_*vid 4 php dependency-injection inversion-of-control laravel

我试图围绕依赖注入和IoC容器,我正在使用我的UserController作为示例.我正在定义UserController在其构造函数中所依赖的内容,然后使用App :: bind()将这些对象绑定到它.如果我正在使用Input :: get()facade/method/thing我没有利用我刚刚注入的Request对象?我是否应该使用以下代码,现在注入Request对象或者doInput :: get()解析为同一个Request实例?我想使用静态外墙,但如果他们决定解除未注入的物体,则不会.

$this->request->get('email');
Run Code Online (Sandbox Code Playgroud)

依赖注入

<?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;
});
Run Code Online (Sandbox Code Playgroud)

UserController的

<?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');
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*wis 10

如果您担心可测试性问题,那么您应该只注入未通过外观路由的实例,因为外观本身已经可测试(意味着您可以在L4中模拟这些).你不应该注入响应,哈希,查看环境,请求等.从它的外观你只需要注入$user.

对于其他一切,我只是坚持使用静态外观.查看基类的swapshouldReceive方法Facade.您可以轻松地使用自己的模拟对象替换基础实例,或者只是开始使用,例如,模拟View::shouldReceive().

希望这可以帮助.

  • 减1用于通过外观提倡以下内容:全局状态,静态调用耦合(特别是对框架),以及用于依赖解析的服务定位器,使您的对象api成为骗子. (2认同)