2015-08-14 79 views
0

在Laravel 5.1中是否有更好的方法來組織或編寫下面的控制器方法?Laravel 5.1中的混亂控制器

我想保持我的控制器簡潔而甜美。我正在使用一個存儲庫設置,因爲我正在構建一個相當大的應用程序,並且希望保持組織的一切。

請提供有關組織下面的代碼的最佳方法。

/** 
* Show the form for creating a new resource. 
* 
* @return Response 
*/ 
public function create(CreateTimesheetRequest $request) 
{ 
    $data     = $request->only('user_id', 'template_id'); 
    $data['submitted_by'] = Auth::user()->id; 

    $timesheetId = $this->timesheet->createTimesheet($data); 

    foreach($request->get('row') as $key => $row) 
    { 
     foreach($row as $field => $value) 
     { 
      $this->timesheet->saveTimesheetRows([ 
       'timesheet_id' => $timesheetId, 
       'field_id'  => $this->timesheetFields->where('name', $field)->first()->id, 
       'field_name' => $field, 
       'field_value' => $value, 
       'field_key'  => $key 
      ]); 
     } 
    } 

    return Redirect::back()->withMessage('The timesheet was successfully created.'); 
} 
+0

哪裏混亂? – RiggsFolly

+0

我只是想知道是否有更好的方式來編寫上述(即通過擺脫嵌套爲每個不知何故) – V4n1ll4

回答

2

所有我可以建議 - 移動這樣的:

$data     = $request->only('user_id', 'template_id'); 
$data['submitted_by'] = Auth::user()->id; 

...到你的請求類。例如,到一些data()方法:

class CreateTimesheetRequest ... { 

    ... 

    public function data() { 
     return array_merge(
      $this->only('user_id', 'template_id'), 
      ['submitted_by' => Auth::user()->id] 
     ); 
    } 

} 

此外,$this->timesheet->saveTimesheetRows(array)看起來更像$this->timesheet->saveTimesheetRow(array)我 - 名打算保存多個行,但你給該方法僅每通話一排。

也許,你可以重構該方法來取消。像這樣:

function saveTimesheetRows($timesheetId, $key, $rows, $fieldIds) { 
    foreach($rows as $field => $value) { 
     $this->saveTimesheetRow([ 
      'timesheet_id' => $timesheetId, 
      'field_id'  => $fieldIds[$field], 
      'field_name' => $field, 
      'field_value' => $value, 
      'field_key'  => $key 
     ]); 
    } 
} 

function saveTimesheetRow(array $row) { 
    // old saveTimesheetRows implementation 
} 

Upd。 而另一小提示:用雄辯的keyBy()方法,像這樣:

$keyIDs = $this->timesheetFields->whereIn('name', $fields)->get(["name", "id"])->keyBy("name"); 

所以,最後:

public function create(CreateTimesheetRequest $request) { 
    $data = $request->data(); 

    $timesheetId = $this->timesheet->createTimesheet($data); 

    foreach($request->get('row') as $key => $row) { 

     $this->timesheet->saveTimesheetRows(
      $timesheetId, 
      $key, 
      $row, 
      $this->timesheetFields 
       ->whereIn('name', array_keys($row)) 
       ->get(["name", "id"]) 
       ->keyBy("name") // probably, can be moved into $this->timesheetFields implementation 
     ); 

    } 

    return Redirect::back()->withMessage('The timesheet was successfully created.'); 
} 
相關問題