我試圖圍繞依賴注入和IoC容器我的頭,我用我的UserController作爲例子。我定義了UserController在其構造函數中依賴的內容,然後使用App :: bind()將這些對象綁定到它。如果我使用Input :: get()facade/method/thing我沒有利用我剛注入的Request對象?我應該使用下面的代碼來代替,現在Request對象被注入或者doInput :: get()解析爲相同的請求實例?我想使用靜態外觀,但是如果它們解析爲未注入的對象則不行。laravel - 依賴注入和IoC容器
$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');
}
減號1用於通過外觀提倡以下內容:全局狀態,靜態調用耦合(特別是框架)和服務定位器,用於解析依賴關係,使對象API成爲騙子。 – Jimbo 2014-11-20 11:16:25
@Jimbo我想你說的是我對Laravel的不安。 – 2015-10-16 08:30:03