Laravel: 避免在控制器中使用构造函数创建模型实例

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();

这种技术有名字吗? (这是一种模式吗?)。

我的理解是,每次调用控制器时,它都会自动生成用户实例 class(模型)并应用别名(引用)属性 $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 检查构造函数是否有 type hinted 参数(那些类型定义为 __construct(Utenti $obj){ 的参数)如果你的控制器有这些 Laravel 中的任何一个都会尝试创建 class 的实例,然后 将其注入 到构造函数中。

这样做的原因是,class(在本例中是您的控制器)的依赖项变得非常清楚。如果您键入提示接口而不是具体的 class,它会变得特别有趣。然后,您必须通过绑定告诉 Laravel 它应该注入接口的哪个实现,但您也可以轻松地交换实现或模拟它以进行单元测试。

您可以通过以下几个链接获取更多信息: