Создание класса обслуживания Laravel - PullRequest
0 голосов
/ 14 сентября 2018

My Uptime.php

<?php 

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.uptimerobot.com/v2/getMonitors",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "Your Api Key",
CURLOPT_HTTPHEADER => array(
  "cache-control: no-cache",
  "content-type: application/x-www-form-urlencoded"
 ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

 if ($err) {
   echo "cURL Error #:" . $err;
} else {
$data = json_decode($response);
$custom_uptime = ($data->monitors[0]->custom_uptime_ratio);
$uptime = explode("-",$custom_uptime);
}

?>

ApiCommand.php

public function handle()
{
   //include(app_path() . '/Includes/Uptime.php')
   $this->showMonitors();
}

public function showMonitors(UptimeRobotAPI $uptime_api)
{
    $monitors = $uptime_api->getMonitors();

    return $monitors;
}

Всем привет.Я просто хочу спросить, как я могу превратить это в класс обслуживания?Нужно ли использовать поставщиков услуг или сервисные контейнеры?Заранее спасибо.

Кто-то преобразовал его в класс обслуживания, и вот моя команда выглядит так.

1 Ответ

0 голосов
/ 14 сентября 2018

В вашем терминале требуется пакет guzzle, поскольку вы будете использовать его в качестве HTTP-клиента: composer require guzzlehttp/guzzle

Тогда вы можете сделать класс для вашего UptimeRobotAPI на app/Services/UptimeRobotAPI.php:

<?php

namespace App\Services;

use GuzzleHttp\Client;

class UptimeRobotAPI
{
    protected $url;
    protected $http;
    protected $headers;

    public function __construct(Client $client)
    {
        $this->url = 'https://api.uptimerobot.com/v2/';
        $this->http = $client;
        $this->headers = [
            'cache-control' => 'no-cache',
            'content-type' => 'application/x-www-form-urlencoded',
        ];
    }

    private function getResponse(string $uri = null)
    {
        $full_path = $this->url;
        $full_path .= $uri;

        $request = $this->http->get($full_path, [
            'headers'         => $this->headers,
            'timeout'         => 30,
            'connect_timeout' => true,
            'http_errors'     => true,
        ]);

        $response = $request ? $request->getBody()->getContents() : null;
        $status = $request ? $request->getStatusCode() : 500;

        if ($response && $status === 200 && $response !== 'null') {
            return (object) json_decode($response);
        }

        return null;
    }

    private function postResponse(string $uri = null, array $post_params = [])
    {
        $full_path = $this->url;
        $full_path .= $uri;

        $request = $this->http->post($full_path, [
            'headers'         => $this->headers,
            'timeout'         => 30,
            'connect_timeout' => true,
            'http_errors'     => true,
            'form_params'     => $post_params,
        ]);

        $response = $request ? $request->getBody()->getContents() : null;
        $status = $request ? $request->getStatusCode() : 500;

        if ($response && $status === 200 && $response !== 'null') {
            return (object) json_decode($response);
        }

        return null;
    }

    public function getMonitors()
    {
        return $this->getResponse('getMonitors');
    }
}

Затем вы можете добавить дополнительные функции, я создал getMonitors() в качестве примера.

Чтобы использовать это в контроллере, вы можете просто добавить его в методы вашего контроллера по зависимости:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\Promises\UptimeRobotAPI;

class ExampleController extends Controller
{
    public function showMonitors(UptimeRobotAPI $uptime_api)
    {
        $monitors = $uptime_api->getMonitors();

        return view('monitors.index')->with(compact('monitors'));
    }
}

Это всего лишь пример, он не обрабатывает никаких ошибок или тайм-аутов, которые могут произойти, это просто для вас, чтобы понять и расширить. Я не знаю, что вы хотите с этим делать, но я не могу написать весь ваш проект, хотя это определенно ответит на ваш вопрос. :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...