Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating laravel service class

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

Hello everyone. I just want to ask how can I turn this to a service class? Do I need to use service providers or service containers? Thanks in advance.

Someone convert it to service class and here was my command looks like.

like image 340
Christian Gallarmin Avatar asked Sep 14 '18 16:09

Christian Gallarmin


1 Answers

In your terminal, require the guzzle package as you will use it as an HTTP client: composer require guzzlehttp/guzzle

Then you can make a class for your UptimeRobotAPI at 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');
    }
}

You can then add more functions beneath, I created getMonitors() as an example.

To use this in a controller, you can simply dependency inject it into your controller methods:

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

This is just an example, this does not handle any errors or timeouts that can occur, this is simply for you to understand and extend. I don't know what you want to do with it, but I can't code your whole project, this will definitely answer your question though. :)

like image 115
emotality Avatar answered Oct 11 '22 16:10

emotality