在 Laravel 中保存表单数据的正确方法是什么(使用注入模型)?

hdw*_*ros 4 php dependency-injection laravel laravel-4

我正在尝试设置一个简单的表单来保存,但要确保我们使用的是最佳实践,例如 DI。

在控制器文件中,我有

public function store()
{
    //get form data
    $data = Input::all();

    $newclient = new Client($data);
    $newclient->save();
    return Redirect::route('clients.index');
}
Run Code Online (Sandbox Code Playgroud)

但这真的不是依赖注入。(对吗?)我像这样注入了模型

public function __construct(\Client $clientmodel)
{
    $this->clientmodel=$clientmodel;
}
Run Code Online (Sandbox Code Playgroud)

如何使用依赖注入正确保存存储功能上的表单数据?

luk*_*ter 5

查看__constructorinIlluminate\Database\Eloquent\Model您可以看到它用于fill()分配传入的值。

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();
    $this->syncOriginal();
    $this->fill($attributes);
}
Run Code Online (Sandbox Code Playgroud)

所以你可以fill()在类被实例化后使用它来做同样的事情:

$this->clientmodel->fill($data)
$this->clientmodel->save();
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想保存它,您可以使用create()

$this->clientmodel->create($data);
Run Code Online (Sandbox Code Playgroud)