我正试图围绕依赖注入和 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');
}