2016-11-25 88 views
3

我有一個功能,在嚴格針對OOP原則的同一時間執行大約5個任務。任何人都可以幫我破曉嗎?特別是在其他函數中調用函數對我來說是一種棘手的問題。PHP:使用單個任務打破函數功能?

public function status(){ 
     $client = new Client(); 
     $notification=Notification::where('active',1)->get(); 
     $status = Status::where('name', 'health')->first(); 
     $default_frequency = 1; 

     foreach ($notification as $note) { 
      $status_health = $note->status('health'); 

      $check_frequency = isset($note->check_frequency) ? intval($note->check_frequency) : $default_frequency; 

      $date = \Carbon\Carbon::parse($status_health['timestamp']); 
      $elapsed_time = $date->diffInMinutes(); 

      if($elapsed_time < $check_frequency){ 
       continue; 
      } 

      $response = $client->get($note->website_url, ['http_errors' => false]); 
      $resCode = $response->getStatusCode(); 

      $note->statuses()->attach($status,['values'=> $resCode === 200 ? 'up' : 'down']); 
     } 
    } 
+2

那麼你逐項5任務你想成爲獨立的方法,有人可能會幫助你 – RiggsFolly

+0

是的。因爲這個類很重要,我會反覆調用不同類的函數。這就是爲什麼我現在要破曉的原因。 –

+0

是的,我知道,但**給我們這個代碼中的5個任務的列表,你相信你想分成5個新的方法**我沒有看到5個單獨的任務,所以我顯然是愚蠢的,需要你的幫助 – RiggsFolly

回答

0

我不認爲你需要改進代碼太多。如果我理解正確,那麼您正嘗試在指定的時間間隔內更新通知的狀態。

這可能是分解成兩個任務:

  1. 讓所有通知,並遍歷他們中的每一個
  2. 更新每個通知的基於某些標準狀態

這裏是我的嘗試改進和簡化你的代碼一點:

Class YourClass { 

    const DEFAULT_FREQUENCY = 1; 

    private $client; 

    public function __construct(Client $clinet) 
    { 
     $this->client = $clinet; 
    } 

    public function status() 
    { 
     $notifications = Notification::where('active', 1)->get(); 
     $status = Status::where('name', 'health')->first(); 

     foreach ($notification as $notification) { 
      $this->updateStatus($notification, $status); 
     } 
    } 

    private function updateStatus(Notification $notification, Status $status) 
    { 
     $status_health = $notification->status('health'); 

     $frequency = $this->getFrequency($notification); 

     $elapsed_time = \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes(); 

     if ($elapsed_time >= $frequency) { 
      $response = $this->client->get($notification->website_url, ['http_errors' => false]); 
      $notification->statuses()->attach($status, [ 
       'values'=> $response->getStatusCode() === 200 ? 'up' : 'down' 
      ]); 
     } 
    } 

    private function getFrequency(Notification $notification) 
    { 
     return isset($notification->check_frequency) 
      ? intval($notification->check_frequency) 
      : self::DEFAULT_FREQUENCY; 
    } 
} 
+0

tnx用於響應。我會閱讀並嘗試它,如果它適用於我....讚賞它 –

+0

完美的預期!我真正想要返回這個類的是,如果響應代碼不是200那麼它應該在不同的類中調用它來發送鬆弛或電子郵件通知?如果我們可以給我提示或幫助? –

+0

你可以在你的類構造函數中注入其他類(類似於我們用'Client'類所做的)。然後,一旦你檢查了你的$回覆代碼,它不是200,你可以調用其他類的方法進行進一步處理(即發送通知) –