Christian Gallarmin
Christian Gallarmin

Reputation: 660

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.

Upvotes: 11

Views: 76272

Answers (2)

Md. Saifur Rahman
Md. Saifur Rahman

Reputation: 404

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

Upvotes: 1

emotality
emotality

Reputation: 13035

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

Upvotes: 35

Related Questions