PHP:用单个任务打破函数功能?

时间:2016-11-25 12:36:16

标签: php laravel

我有一个函数可以同时执行大约5个任务,严格违反OOP原则。有谁能帮我打破它的黎明?特别是在其他函数中调用函数对我来说是一种棘手的问题。

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']);
        }
    }

1 个答案:

答案 0 :(得分:0)

我认为你不需要过多地改进代码。如果我理解正确,您会尝试在指定的时间间隔内更新通知状态。

这可以分为两个任务:

  1. 获取所有通知并循环遍历每个通知
  2. 根据某些条件更新每个通知的状态
  3. 我试图稍微改进和简化您的代码:

    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;
        }
    }