Как я могу оптимизировать отправку push-уведомлений в CodeIgniter PHP? - PullRequest
0 голосов
/ 08 октября 2018

Проблема Я пытаюсь отправить push-уведомление через PHP на Android и iOS, но у меня есть много устройств для отправки уведомления, и вы можете увидеть код, который отправляет уведомление всемиз них в цикле.Это действительно не оптимизировано, так как моя панель управления застревает более чем на минуту из-за цикла выполнения, а также почему-то даже не отправляет уведомление всем активным учетным записям.

Может ли кто-нибудь здесь помочь мне?

Код

public function insert()
{
    // Set the validation rules
    $this->form_validation->set_rules('title', 'Title', 'required|trim');

    // If the validation worked
    if ($this->form_validation->run())
    {
        $get_post = $this->input->get_post(null,true);
        $get_post['tags'] = is_array($this->input->get_post('tags')) ? $this->input->get_post('tags') : [];

        if(count($get_post['tags']) == 0)
        {
            $_SESSION['msg_error'][] = "Tags is a required field";
            redirect('admin/newsfeed/insert');
            exit;
        }

        # File uploading configuration
        $upload_path = './uploads/newsfeeds/';
        $config['upload_path'] = $upload_path;
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['encrypt_name'] = true;

        $this->load->library('upload', $config);

        $image = '';
        # Try to upload file now
        if ($this->upload->do_upload('image'))
        {
            # Get uploading detail here
            $upload_detail = $this->upload->data();
            $image = $upload_detail['file_name'];
        } else {
            $uploaded_file_array = (isset($_FILES['image']) and $_FILES['image']['size'] > 0 and $_FILES['image']['error'] == 0) ? $_FILES['image'] : '';
            # Show uploading error only when the file uploading attempt exist.
            if( is_array($uploaded_file_array) )
            {
                $uploading_error = $this->upload->display_errors();
                $_SESSION['msg_error'][] = $uploading_error;
            }
        }

        # File uploading configuration
        $upload_path = './uploads/newsfeeds/';
        $config['upload_path'] = $upload_path;
        $config['allowed_types'] = '*';
        $config['encrypt_name'] = true;
        $config['max_size'] = 51200; //KB

        $this->upload->initialize($config);

        $audio = '';
        # Try to upload file now
        if ($this->upload->do_upload('audio'))
        {
            # Get uploading detail here
            $upload_detail = $this->upload->data();
            $audio = $upload_detail['file_name'];
        }
        else
        {
            $uploaded_file_array = (isset($_FILES['audio']) and $_FILES['audio']['size'] > 0 and $_FILES['audio']['error'] == 0) ? $_FILES['audio'] : '';
            # Show uploading error only when the file uploading attempt exist.
            if( is_array($uploaded_file_array) )
            {
                $uploading_error = $this->upload->display_errors();
                $_SESSION['msg_error'][] = $uploading_error;
            }
        }

        $get_post['image'] = $image;
        $get_post['audio'] = $audio;


        if($id = $this->newsfeed_model->insert($get_post))
        {
            if($get_post['status'])
            {
                // send push notification to all users
                $notification = $this->newsfeed_model->get_newsfeed_by_id($id);
                $notification->notification_type = 'article';
                $notification->title = $get_post['n_title'];
                $notification->body = $get_post['n_description'];

                $query = $this->db->get_where('users', ['device_id !=' => '']);
                foreach ($query->result() as $row) {
                    if ($row->device == 'IOS') {
                        $this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
                    }
                    if ($row->device == 'ANDROID') {
                        $this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
                    }
                }
            }
            $_SESSION['msg_success'][] = 'Record added successfully...';
            if($image){
                redirect('admin/newsfeed/crop_image?id='.$id);
            } else {
                redirect('admin/newsfeed/');
            }
        }
    }

    $this->data['selected_page'] = 'newsfeed';
    $this->load->view('admin/newsfeed_add', $this->data);
}

Описание Метод добавляет ленту новостей, проверяет проверки, затем вставляет ленту в базу данных.После этого он отправляет уведомление всем устройствам.

Проблемный блок

if($id = $this->newsfeed_model->insert($get_post))
{
    if($get_post['status'])
    {
        // send push notification to all users
        $notification = $this->newsfeed_model->get_newsfeed_by_id($id);
        $notification->notification_type = 'article';
        $notification->title = $get_post['n_title'];
        $notification->body = $get_post['n_description'];

        $query = $this->db->get_where('users', ['device_id !=' => '']);
        foreach ($query->result() as $row) {
            if ($row->device == 'IOS') {
                $this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
            }
            if ($row->device == 'ANDROID') {
                $this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
            }
        }
    }

    $_SESSION['msg_success'][] = 'Record added successfully...';
    if($image) {
        redirect('admin/newsfeed/crop_image?id='.$id);
    } else{
        redirect('admin/newsfeed/');
    }
}

Заранее спасибо.

...