[英]Laravel: Avoid to create instance of a model with a constructor in the controller
我正在學習Laravel 4的課程,老師進行了代碼重構,並在控制器中引入了魔術方法構造函數
class UtentiController extends BaseController {
protected $utente;
public function __construct(Utenti $obj) {
$this->utente = $obj;
}
public function index() {
$utenti = $this->utente->all();
return View::make('utenti.index', ["utenti" => $utenti]);
}
public function show($username) {
$utenti = $this->utente->whereusername($username)->first(); //select * from utenti where username = *;
return View::make('utenti.singolo', ["utenti" => $utenti]);
}
public function create() {
return View::make('utenti.create');
}
public function store() {
if (! $this->utente->Valido( $input = Input::all() ) ) {
return Redirect::back()->withInput()->withErrors($this->utente->messaggio);
}
$this->utente->save();
return Redirect::route('utenti.index');
}
}
由於有了這段代碼,我不必每次都創建一個新的Utenti
模型實例:
protected $utente;
public function __construct(Utenti $obj) {
$this->utente = $obj;
}
現在,我可以使用以下簡單方法訪問數據庫:
$this->utente->all();
而以前,我必須這樣做:
$utente = new Utente;
$utente::all();
這種技術有名稱嗎? (這是一種模式嗎?)。
我的理解是,每次調用控制器時,它都會自動生成User類(模型)的實例並應用別名(引用)屬性$utente
那是對的嗎?
另外,這是Utenti
模型的代碼:
class Utenti extends Eloquent {
public static $regole = [
"utente" => "required",
"password" => "required"
];
public $messaggio;
public $timestamps = false;
protected $fillable = ['username','password'];
protected $table = "utenti";
public function Valido($data) {
$validazione = Validator::make($data,static::$regole);
if ($validazione->passes()) return true;
$this->messaggio = $validazione->messages();
return false;
}
}
這稱為依賴注入或短DI。 在創建Controller的新實例時,Laravel會在構造函數中檢查類型提示的參數(類型定義如__construct(Utenti $obj){
參數)的參數。並且它注入到構造。
這樣做的原因是,變得非常清楚類(在本例中為控制器)的依賴關系是什么。 如果鍵入提示而不是具體的類,則將變得特別有趣。 然后,您必須通過綁定告訴Laravel應該注入哪個接口實現,但是您也可以輕松地交換實現或模擬它以進行單元測試。
以下是一些鏈接,您可以在其中獲得更多信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.