简化在其他控制器中使用的代码

时间:2019-05-21 22:21:51

标签: php laravel

是否可以简化此方法以用于各种控制器方法?

$eventId = request()->route('event');
$event = Event::where('id', $eventId)->first();
if($event->finish == 0) {
    return $content
        ->header(__('Timing'))
        ->description(__('List'))
        ->body($this->grid());
}
else {
    return $content
            ->header(__('Start list'))
            ->description(__('List'))
            ->body(view('admin.events.finished'));
}

唯一更改的是标头,描述和正文  当finish等于0时,其他所有元素都相同。

谢谢

2 个答案:

答案 0 :(得分:0)

您可以将要点保存在模型中,然后在需要时调用它。

public function event ($eventId){
   $event = Event::where('id', $eventId)->first();

   if($event->finish == 0) {
     $outcome = $content ->header(__('Timing')) 
          ->description(__('List')) ->body($this->grid()); 

  } else { 
    $outcome = $content ->header(__('Start list')) 
            ->description(__('List'))
             ->body(view('admin.events.finished')); 
  }

   return $outcome;
  }

答案 1 :(得分:0)

您的控制器中没有太多逻辑,因此这还不是很糟糕。但是可以。我注意到的几件事是$event->finish == 0,首先我会在您的模型上创建一个范围

public function isFinished()
{
    return $this->finish == 0;
}

您究竟如何获得EventId?我可以想象它是通过参数传递的?所以您应该能够将其作为依赖项?

public function YourcontrollerFunction(Request $request, $eventId)
{
    //Either you get the request from a parameter or the $request->event_id
}

因此,一个小的重构总看起来像这样:

public function YourcontrollerFunction(Request $request, $eventId)
{
    $event = Event::findOrFail($eventId);
    if($event->isFinished()) {
        return $content
           ->header(__('Timing'))
           ->description(__('List'))
           ->body($this->grid());
    }
//No need for the else.
   return $content
     ->header(__('Start list'))
     ->description(__('List'))
     ->body(view('admin.events.finished'));
}

如果经常使用响应,则可以创建一个Response类,该类也存储了,但是在这里看不到这个原因。