[英]laravel - dependency injection and the IoC Container
我試圖圍繞依賴注入和IoC容器,我正在使用我的UserController作為示例。 我正在定義UserController在其構造函數中所依賴的內容,然后使用App :: bind()將這些對象綁定到它。 如果我正在使用Input :: get()facade / method / thing我沒有利用我剛剛注入的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;
});
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');
}
如果您擔心可測試性問題,那么您應該只注入未通過外觀路由的實例,因為外觀本身已經可測試(意味着您可以在L4中模擬這些)。 您不需要注入響應,哈希,查看環境,請求等。從它的外觀來看,您只需要注入$user
。
對於其他一切,我只是堅持使用靜態外觀。 查看基本Facade
類上的swap
和shouldReceive
方法。 您可以使用自己的模擬對象輕松地交換基礎實例,或者只是使用View::shouldReceive()
開始View::shouldReceive()
。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.