创建 laravel 服务类



我的正常运行时间.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;
}

大家好。我只想问我怎样才能把它变成服务类?我是否需要使用服务提供商或服务容器?提前谢谢。

有人将其转换为服务类,这是我的命令的样子。

在终端中,需要guzzle包,因为您将它用作 HTTP 客户端:composer require guzzlehttp/guzzle

然后,您可以在app/Services/UptimeRobotAPI.php为您的UptimeRobotAPI制作一个类:

<?php
namespace AppServices;
use GuzzleHttpClient;
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 AppHttpControllers;
use IlluminateHttpRequest;
use AppServicesPromisesUptimeRobotAPI;
class ExampleController extends Controller
{
public function showMonitors(UptimeRobotAPI $uptime_api)
{
$monitors = $uptime_api->getMonitors();
return view('monitors.index')->with(compact('monitors'));
}
}

这只是一个例子,它不处理可能发生的任何错误或超时,这只是为了让您理解和扩展。我不知道你想用它做什么,但我不能编码你的整个项目,这肯定会回答你的问题。:)

创建服务类

  • 在此文件夹中app/Services/ExportBookingService.php
<?php
namespace AppServices;
use IlluminateSupportFacadesDB;
use AppModelsExportExportBooking;
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!']];
}
}
}

在控制器中像这样使用:

<?php
namespace AppHttpControllersExport;
use AppTraitsApiResponser;
use AppHttpControllersController;
use AppModelsExportExportBooking;
use AppServicesModulesExportExportBookingService;
use AppHttpRequestsModulesExportExportBookingExportBookingCreateRequest;

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

}

最新更新