medianet-dev/p-connector

使用 RESTful API 将项目链接在一起

1.7.6 2024-09-11 10:30 UTC

README


StyleCI

PConnector 是一个包,使得将项目链接在一起比手动执行 GuzzleCurl 请求要简单得多。您只需要设置您网关的一些基本设置即可。

安装

您可以通过 composer 安装此包

composer require medianet-dev/p-connector

然后运行以下命令迁移包表

php artisan migrate

使用

在这里,我们将通过一些示例来展示如何进行基本和高级 API 调用。

配置您的网关

在开始使用此包之前,您需要为您的网关设置一个配置文件,为此,您需要通过运行以下命令来发布配置文件

php artisan vendor:publish --provider="MedianetDev\PConnector\PConnectorServiceProvider"

发布配置后,请转到 p-connector.php 配置文件并设置您的第一个配置文件设置

# file: p-connector.php

/*
|--------------------------------------------------------------------------
| List of the available profiles with it's configurations
|--------------------------------------------------------------------------
*/
'profiles' => [
    'demo' => [
        'protocol' => 'https',
        'host' => 'my-json-server.typicode.com',
        'port' => 443,
        'prefix' => 'typicode/demo',
    ],
],

请注意,您可以设置 多个 配置文件。

以上是基本配置,其他可用设置请参阅配置文件本身。

一些使用示例

// Import the PConnector facade to get available methods hints 
use MedianetDev\PConnector\Facade\PConnector;

// Or use tha alias without available methods hints
# use PConnector;

// Method 1:
$demo = PConnector::get('posts/1');
echo '<h1>'.$demo->title.'</h1>';

// Method 2:
# $demo = PConnector::send('posts/1', [], 'GET');
# echo '<h1>'.$demo->title.'</h1>';

如果我们设置了 default_profile 参数,我们不必告诉 PConnector 使用哪个配置文件,但如果我们有多个配置文件并且我们想在这之间切换,我们可以使用 profile() 函数,如下所示

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::profile('demo')->get('posts/1');
$demo2 = PConnector::profile('demo_2')->get('users/1');

重要:配置文件函数将应用特定的配置文件配置并 清除 任何其他设置,因此如果您想切换配置文件,请先调用 profile() 函数,然后再调用其他任何函数。

配置

一些设置可以作为配置文件设置,您将找到带有 [AAPS] 注释的这些设置以区分它们(AAPS:也是配置文件设置)。要为配置文件设置设置,您必须将它们放入适当的配置文件数组中。另外,如果设置在配置文件内部定义为配置文件和全局同时存在,则将使用配置文件中的设置。

HTTP 方法

send(string $path = '', array $data = [], string $method = 'GET')
post(string $path = '', array $data = [])
get(string $path = '', array $data = [])
put(string $path = '', array $data = [])
patch(string $path = '', array $data = [])
delete(string $path = '', array $data = [])

身份验证

PConnector 支持使用身份验证发送请求,要这样做,您需要为所需的配置文件或所有配置文件配置身份验证设置。

# file: p-connector.php

'auth' => [ // [AAPS]
    // Whether to use authentication by default or not (you can make an exception with withAuth() and withoutAuth() methods)
    'authenticate_by_default' => false,
    // How to authenticate (Accepted values are: api_key, basic, bearer)
    'auth_method' => 'bearer',
    // If the api_key method is use then you SHOULD provide an api_key key
    // 'api_key' => 'X-AUTH-TOKEN',
    // The path of the login
    'login_path' => 'login',
    // The http method used to login
    'login_http_method' => 'POST',
    'credentials' => [
        'username' => 'username',
        'password' => 'password',
    ],
    // The expected http code response when login in
    'success_login_code' => [200],
    // When should we re-authenticate
    're_auth_on_codes' => [401],
    // Where to find the token in the response (you can youse the dot syntax EX: 'data.user.auth.token')
    'token_path' => 'token',
],

您可以通过在配置文件中添加 auth 数组来配置所需的配置文件的身份验证设置。

'profiles' => [
    'demo' => [
        ...,
        'auth' => [ // Add this section for custom auth settings
            // Authentication settings specific to this profile
        ],
    ],
],

如果由于某些原因您在发送某些请求时不想包含身份验证,您可以像这样告诉 PConnector

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::profile('demo')->withoutAuth()->get('posts/1');
# $demo = PConnector::withoutAuth()->get('users/1');

请记住,配置文件函数将应用特定的配置文件配置并 清除 任何其他设置(在我们的情况下是 withoutAuth() 函数),这就是为什么我们在 withoutAuth() 之前使用 profile() 的原因。

请求

# file: p-connector.php

// Request settings
'request' => [ // [AAPS]
    // The default request headers
    'headers' => ['Accept' => 'application/json'],
    // Whether to send the language through the header by default or not
    'enable_localization' => true,
    // Handle http errors or not
    'http_errors' => false,
    // Http connect timeout value
    'connect_timeout' => 3,
    // Http timeout value
    'timeout' => 3,
    // The data type; json, form-data, ...
    'post_data' => 'json',
],
本地化

当需要时发送 Accept-Language

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::lang('ar')->get('posts/1');

或者通过配置文件自动配置 PConnector 来发送它。

快速更改当前 URL
PConnector::url('https://jsonplaceholder.typicode.com')->get('todos')

或者您可以使用 setUrl() 方法别名

这是可用于请求的获取器列表
  • getRequestUrl()
  • getRequestMethod()
  • getRequestData()

响应

您可以根据需要配置如何保存响应体

  • 作为字符串
  • 作为对象
  • 作为数组
# file: p-connector.php

'decode_response' => 'object', // [AAPS]

如果您想为特定响应更改此设置

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::objectResponse()->get('posts/1');
$demo = PConnector::htmlResponse()->get('posts/1');
$demo = PConnector::arrayResponse()->get('posts/1');

在发送请求后,可以使用 getResponseBody() 获取接收到的响应体。

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::get('posts/1')->getResponseBody();

这是可用于响应的获取器列表

  • getResponseBody()
  • getResponseStatusCode()
  • getResponseHeaders()

如果您将响应体解码为对象,可以使用 getAttribute('attribute_name')->attribute_name 来获取特定属性,或者您可以更深入地进行,例如使用 getAttribute('object.object.attribute_name', 'fallback value')

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::get('posts/1')->getAttribute('title');
$demo = PConnector::get('posts/1')->title;
$demo = PConnector::get('posts/1')->getAttribute('author.name', 'Unknown author');

响应状态码检查

  • 函数 responseCodeIs(int $code): bool
  • 函数 responseCodeNot(int $code): bool
  • 函数 responseCodeIn(array $codes): bool
  • 函数 responseCodeNotIn(array $codes): bool
  • 函数 responseOK(): bool
  • 函数 responseNOK(): bool

示例

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::get('posts/1');
if ($demo->responseCodeNot(200)) {
    echo 'This is not what I was expecting from Demo!';
} else {
    echo '<h1>'.$demo->title.'</h1>';
}

$demo = PConnector::post('posts', ['title' => 'My title']);
 if ($demo->responseCodeNotIn([200, 201])) {
    echo 'This is not what I was expecting from Demo!';
} else {
    echo 'Post created, Hola!';
}

日志记录

# file: p-connector.php

// Log requests & responses to log files or not (you can make an exception with withLog() and withoutLog() methods)
'log' => false, // [AAPS]

示例 1

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::get('posts/1')->dump();

if ($demo->responseCodeNot(200)) {
    $demo->log();
} else {
    echo '<h1>'.$demo->title.'</h1>';
}

示例 2

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::withLog()->get('posts/1');

调试

您可以使用 dump()dd() 方法来调试 PConnector 对象。

use MedianetDev\PConnector\Facade\PConnector;

$demo = PConnector::get('posts/1')->dump();
$demo = PConnector::get('posts/1')->dd();

更新日志

有关最近更改的更多信息,请参阅 更新日志

贡献

有关详细信息,请参阅 贡献指南

安全性

如果您发现任何安全相关的问题,请通过电子邮件 soufiene.slimi@medianet.com.tn 报告,而不是使用问题跟踪器。

鸣谢

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件