首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IoC依赖注入和laravel容器

问IoC依赖注入和laravel容器
EN

Stack Overflow用户
提问于 2013-04-05 09:55:04
回答 1查看 4.4K关注 0票数 4

我正在尝试理解依赖注入和IoC容器,并以我的UserController为例。我在构造函数中定义了UserController依赖的内容,然后使用App::bind()将这些对象绑定到它。如果我使用的是Input::get() facade/method/thing,那么我是不是没有利用刚才注入的Request对象呢?既然请求对象已经被注入,或者不使用is::get()解析到相同的请求实例,我应该使用下面的代码吗?我喜欢使用静态外观,但如果它们解析为未注入的对象,则不会使用静态外观。

代码语言:javascript
复制
$this->request->get('email');

依赖注入

代码语言:javascript
复制
<?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;
});

UserController

代码语言:javascript
复制
<?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');
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-06 16:50:52

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

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

希望这能有所帮助。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15824673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档