我正在尝试理解依赖注入和IoC容器,并以我的UserController为例。我在构造函数中定义了UserController依赖的内容,然后使用App::bind()将这些对象绑定到它。如果我使用的是Input::get() facade/method/thing,那么我是不是没有利用刚才注入的Request对象呢?既然请求对象已经被注入,或者不使用is::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;
});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');
}发布于 2013-04-06 16:50:52
如果你担心可测试性,那么你真的应该只注入那些没有通过外观路由的实例,因为外观本身已经是可测试的(这意味着你可以在L4中模拟它们)。你不应该需要注入响应,哈希器,视图环境,请求等等。从外观上看,你只需要注入$user。
对于其他所有东西,我只会坚持使用静态外观。查看Facade基类上的swap和shouldReceive方法。您可以轻松地用自己的模拟对象替换底层实例,或者简单地开始模拟,例如,使用View::shouldReceive()。
希望这能有所帮助。
https://stackoverflow.com/questions/15824673
复制相似问题