创建laravel服务类 [英] Creating laravel service class

查看:142
本文介绍了创建laravel服务类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Uptime.php

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

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.

推荐答案

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

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

然后您可以在app/Services/UptimeRobotAPI.php上为UptimeRobotAPI进行授课:

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

然后您可以在下面添加更多功能,以我创建的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. :)

这篇关于创建laravel服务类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆