【问题标题】:laravel - dependency injection and the IoC Containerlaravel - 依赖注入和 IoC 容器
【发布时间】:2013-04-05 01:55:04
【问题描述】:

我正试图围绕依赖注入和 IoC 容器展开思考,并以我的 UserController 为例。我在其构造函数中定义了 UserController 所依赖的内容,然后使用 App::bind() 将这些对象绑定到它。如果我正在使用 Input::get() 外观/方法/事物,我是否没有利用我刚刚注入的 Request 对象?我应该改用以下代码吗,既然 Request 对象被注入或 doInput::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');
}

【问题讨论】:

    标签: php dependency-injection inversion-of-control laravel


    【解决方案1】:

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

    对于其他所有事情,我都会坚持使用静态外观。查看基于 Facade 类的 swapshouldReceive 方法。您可以轻松地用自己的模拟对象替换底层实例,或者简单地开始模拟,例如,View::shouldReceive()

    希望这会有所帮助。

    【讨论】:

    • 通过外观倡导以下内容的减 1:全局状态、耦合的静态调用(特别是到框架)以及用于依赖解析的服务定位器,使您的对象 api 成为骗子。
    • @Jimbo 我认为你所说的是我对 Laravel 的不安的基础。
    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多