11

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.

4
  • github.com/guzzle/guzzle
    – emotality
    Sep 14, 2018 at 16:51
  • @emotality can you explain to me how it makes service class caused I'm so confused :/ Sep 14, 2018 at 16:58
  • This is too broad. A service class isn't anything special, study OOP and SOLID. Sep 14, 2018 at 17:07
  • I'll paste something now. :)
    – emotality
    Sep 14, 2018 at 17:12

2 Answers 2

33

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. :)

4
  • 1
    If your POST have issues, I'll give alternative.
    – emotality
    Sep 14, 2018 at 17:37
  • I only had a simple concern, what you did is right. I appreciated your effort and work. Basically I had three different classes and one of that is the Uptime that you did. I want to use that on my console command which before I had to include(app_path() . '/Includes/Uptime.php')); Sep 14, 2018 at 19:17
  • Can you have a look at my code above and check if I'm at the right path? Thank you. Sep 14, 2018 at 19:57
  • I am creating a reporting tool to check all my GA , Crawl Reports and Uptime, My command is the one who creates the blade file and get the values from my three classes that mention. Sorry for late response I have a work on weekends :/ I hope you still response when you have time. Thank you. Sep 17, 2018 at 1:46
0

Create Service class

  • In this folder app/Services/ExportBookingService.php
<?php

namespace App\Services;
use Illuminate\Support\Facades\DB;
use App\Models\Export\ExportBooking;

class ExportBookingService
{

    public function create($request)
    {
        $max_operation_id = max_operation_id();

        DB::beginTransaction();
        try {
            $export_booking = ExportBooking::create(
                [

                    'booking_number' => $this->generateBookingNumber($request),
                    'booking_date' => $request->booking_date ?? null,
                    'exp_organization_id' => $request->exp_organization_id ?? null,

                    'created_at' => getNow(),
                    'created_by' => auth()->user()->id,
                ]);

           
            DB::commit();

            $data = ExportBooking::with('exp_booking_dtl','exp_booking_rev','export_pi','exp_booking_status','organization','exp_lc_tenure','customer','brand','sales_mode')
                    ->where('id', $export_booking['id'])->first();

            return [$data,  200,'success', ['Export Booking Created']];
        } catch (\Exception $e) {
            DB::rollback();
            $logMessage = formatCommonErrorLogMessage($e);
            writeToLog($logMessage, 'debug');
            return [null,  422,'error', ['Something went wrong. Please try again later!']];
        }
    }
}

In Controller Use like this :

<?php

namespace App\Http\Controllers\Export;

use App\Traits\ApiResponser;
use App\Http\Controllers\Controller;
use App\Models\Export\ExportBooking;
use App\Services\Modules\Export\ExportBookingService;
use App\Http\Requests\Modules\Export\ExportBooking\ExportBookingCreateRequest;


class ExportBookingController extends Controller
{
    use ApiResponser;

    protected $exportBookingService;

    public function __construct(ExportBookingService $exportBookingService)
    {
        $this->exportBookingService = $exportBookingService;
    }

    public function bookingCreate(ExportBookingCreateRequest $request)
    {
        try {
            [$res_data, $res_code, $res_status, $res_msg]= $this->exportBookingService->create($request);

            return $this->set_response($res_data, $res_code,$res_status, $res_msg, $request->merge(['log_type_id' => 3,'segment'=>'Export Booking Create','pagename'=>'Export Booking Create','pageurl'=>'/export/booking']));
        } catch (\Exception $e) {
            $logMessage = formatCommonErrorLogMessage($e);
            writeToLog($logMessage, 'debug');
            return $this->set_response(null,  422,'error', ['Something went wrong. Please try again later!']);
        }
    }
   
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.