定制 motomedialab/connector 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

motomedialab/connector

Composer 安装命令:

composer require motomedialab/connector

包简介

A super lightweight request/connector pattern to make light work of API authentication and calls

README 文档

README

MIT License Latest Version on Packagist Total Downloads Tests

A super lightweight, opinionated connector pattern for Laravel to make light work of consuming third-party APIs.

Introduction

Integrating with external APIs often involves repetitive boilerplate for handling authentication, endpoints, and requests. This package provides a structured and reusable pattern to streamline this process, keeping your code clean, consistent, and easy to maintain.

Installation

You can install the package via composer:

composer require motomedialab/connector

Core Concepts

The package is built around two core concepts: Connectors and Requests.

Connectors

The Connector is responsible for defining the base URL and authentication method for an API. Your connector must extend the Motomedialab\Connector\BaseConnector abstract class.

// app/Connectors/ExampleConnector.php
use Illuminate\Http\Client\PendingRequest;
use Motomedialab\Connector\BaseConnector;

class ExampleConnector extends BaseConnector
{
    /**
     * Optionally authenticate all requests from this connector.
     * For example, an access or bearer token. 
     */
    public function authenticateRequest(PendingRequest $request): PendingRequest
    {
        return $request->withToken('your-secret-token');
    }

    /**
     * Define the base URL for the API you are connecting with
     */
    public function apiUrl(): string
    {
        return 'https://api.example.com/v2/';
    }
}

Requests

The Request defines the specific details of an API call, such as the endpoint, method, headers, and payload. Your request classes must extend the Motomedialab\Connector\BaseRequest abstract class and should implement the Motomedialab\Connector\Contracts\RequestInterface contract.

The BaseRequest provides sensible defaults, so you only need to define what you need to override.

Simple GET Request

Here's a minimal example for a simple GET request:

// app/Requests/ExampleGetRequest.php
use Illuminate\Http\Client\Response;
use Motomedialab\Connector\BaseRequest;
use Motomedialab\Connector\Contracts\RequestInterface;

/**
 * @implements RequestInterface<array>
 */
readonly class ExampleGetRequest extends BaseRequest implements RequestInterface
{
    public function __construct(private string $id)
    {
       //
    }

    public function endpoint(): string
    {
        return "users/{$this->id}";
    }
    
    public function toResponse(Response $response): array
    {
        return $response->json();
    }
}

Advanced POST Request

This example demonstrates all available methods for customising a request.

// app/Requests/ExamplePostRequest.php
use Illuminate\Http\Client\Response;
use Motomedialab\Connector\BaseRequest;
use Motomedialab\Connector\Enums\RequestMethod;
use Motomedialab\Connector\Contracts\RequestInterface;

/**
 * @implements RequestInterface<array>
 */
readonly class ExamplePostRequest extends BaseRequest implements RequestInterface
{
    public function __construct(public array $inputData = [])
    {
      //
    }

    // Define the HTTP method. Defaults to GET.
    public function method(): RequestMethod
    {
        return RequestMethod::POST;
    }
    
    // Specify the request timeout in seconds. Defaults to 5.
    public function timeout(): int
    {
        return 10;
    }
    
    // Add query parameters to the URL.
    public function queryParams(): array
    {
        return ['include' => 'posts'];
    }
    
    // Add or override headers. Defaults include JSON content type.
    public function headers(): array
    {
        return [
            ...parent::headers(),
            'X-Custom-Header' => 'CustomValue',
        ];
    }

    // REQUIRED: Define the endpoint, appended to the connector's apiUrl.
    public function endpoint(): string
    {
        return 'users';
    }

    // Define the request payload.
    public function body(): array
    {
        return $this->inputData;
    }
    
    // Determine if the request requires authentication. Defaults to true.
    public function authenticated(): bool
    {
        return true;
    }

    // Transform the successful response.
    public function toResponse(Response $response): array
    {
        if ($response->failed()) {
            // You can handle error responses here.
            // For example, return a default structure or throw an exception.
            return ['error' => true, 'status' => $response->status()];
        }
        
        return $response->json();
    }
}

Usage

Sending a Request

To send a request, simply instantiate your connector and request, then call the send() method.

$connector = new ExampleConnector();
$request = new ExamplePostRequest(['name' => 'Chris']);

// The response will be whatever you return from toResponse()
$response = $connector->send($request);

Asynchronous Requests

You can also send requests concurrently using the sendAsync() method. This is great for performance when you need to make multiple independent API calls.

use GuzzleHttp\Promise\Utils;

$connector = new ExampleConnector();

// Create an array of requests
$requests = [
    new ExampleGetRequest('user-1'),
    new ExampleGetRequest('user-2'),
    new ExampleGetRequest('user-3'),
];

// Map requests to promises
$promises = array_map(
    fn($request) => $connector->sendAsync($request),
    $requests
);

// Wait for all promises to resolve
$responses = Utils::unwrap($promises);

Testing

This package is designed to work seamlessly with Laravel's Http::fake(). You can write your tests as you normally would.

use Illuminate\Support\Facades\Http;
use App\Connectors\ExampleConnector;
use App\Requests\ExampleGetRequest;

it('sends a get request', function () {
    Http::fake([
        'api.example.com/*' => Http::response(['name' => 'John']),
    ]);

    $connector = new ExampleConnector();
    $response = $connector->send(new ExampleGetRequest('user-1'));
    
    expect($response['name'])->toBe('John');
});

Contributing

Please see CONTRIBUTING for details.

License

The MIT License (MIT). Please see License File for more information.

motomedialab/connector 适用场景与选型建议

motomedialab/connector 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 701 次下载、GitHub Stars 达 2, 最近一次更新时间为 2026 年 01 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「Guzzle」 「connector」 「laravel-http」 「motomedialab」 「request-pattern」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 motomedialab/connector 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 motomedialab/connector 我们能提供哪些服务?
定制开发 / 二次开发

基于 motomedialab/connector 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 701
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 9
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-15