Laravel -我知道我的ViewModel,所以我可以通过控制器参数传递ViewModel


Laravel - I know my ViewModel, so can i pass that ViewModel through into the controller parameters?

我有一个ViewModel和一个控制器方法:

class TimesheetViewModel
{
    public /* TimesheetTotals */ $TimesheetTotals;
    public /* TimesheetEntry[] */ $Timesheets = array();   
    public /* int */ $AmountOfTimesheetEntries = 1;
}
...
public /* void */ function GetCreate()
{
    ...
    $timesheetViewModel = new TimesheetViewModel();
    ...            
    $timesheetViewModel->TimesheetTotals = $timesheetLogic->ColumnSum( $timesheetEntries );
    $timesheetViewModel->AmountOfTimesheetEntries = count( $timesheetEntries );
    $timesheetViewModel->Timesheets = $timesheetEntries;
    return View::make( 'Timesheet/Create', array( "Model" => $timesheetViewModel ) );
}
...

我有一个表单在我的视图,有一个完美的复制属性在我的视图模型…有没有办法在我的控制器中有这样的东西:

...
public /* void */ function PostCreate( TimesheetViewModel $timesheetViewModel )
{
    // This will help because I do not have to do Input::all
    // and then map it (Or not map it at all and stick with 
    // an array that could change when someone is working on 
    // the form fields mucking things up) ?
}
...

看一下表单模型绑定:http://laravel.com/docs/html#form-model-binding

因为你的表单在你的模型中有一个完美的属性复制,你可以在你的控制器中做这样的事情:

public function update($id)
{
    $timesheetViewModel = TimeSheetViewModel::find($id);
    if (!$timesheetViewModel->update(Input::all())) {
        return Redirect::back()
                ->with('message', 'Your time sheet was unable to be saved')
                ->withInput();
    }
    return Redirect::route('timesheet.success')
                ->with('message', 'Your timesheet was updated.');
}

需要注意的是:您将需要使用以下Blade命令打开表单:

{{ Form::model($timeSheetViewModel, array('route' => array('timeSheetViewModel.update', $timeSheetViewModel->id))) }}

$timeSheetViewModel只是任何时间表视图模型,你将传入,为了更新。