我试图总结依赖注入和IoC容器围绕我的头,我用我的UserController中作为一个例子。 我定义什么是由于UserController在其构造取决于然后我使用App ::绑定绑定这些对象是()。 如果我使用的输入::得到()正面/方法/事情我不能走,我只是注入它的Request对象的优势在哪里? 我应该使用下面的代码代替,现在的Request对象注入或doesInput ::得到()解析为相同的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;
});
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');
}