定制 hoodslyhub/order-service-client 二次开发

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

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

hoodslyhub/order-service-client

最新稳定版本:1.0.0

Composer 安装命令:

composer require hoodslyhub/order-service-client

包简介

A framework-agnostic PHP client for HoodslyHub Order API

README 文档

README

A comprehensive PHP client library for the HoodslyHub Order Management API with advanced caching capabilities.

Features

  • Complete Order Management: Create, read, update, delete operations
  • BOL Generation: Generate Bills of Lading for orders
  • Advanced Caching: Intelligent response caching with multiple adapters
  • Smart Cache Invalidation: Automatic cache clearing when data changes
  • Performance Optimization: Up to 90% faster response times
  • Multiple Cache Backends: Filesystem, Redis, WordPress, and custom adapters
  • Authentication Handling: Automatic token management and refresh
  • PSR-16 Caching: Built-in caching support for performance optimization
  • PSR-3 Logging: Comprehensive logging with configurable log levels
  • Error Handling: Detailed exception handling with HTTP status codes
  • Framework Integration: Ready-to-use adapters for popular PHP frameworks
  • PHP 7.2+ Compatible: Supports PHP 7.2 through PHP 8.3+
  • Production Ready: Battle-tested with enhanced caching system

Installation

Install via Composer:

composer require hoodslyhub/order-service-client

Requirements

  • PHP 7.2 or higher (tested on 7.2, 7.3, 7.4, 8.0, 8.1+)
  • Guzzle HTTP client (6.5+ or 7.0+)
  • PSR-16 compatible cache implementation (optional)
  • PSR-3 compatible logger (optional)

Usage

Basic Usage

use HoodslyHub\OrderService\Client\OrderClient;
use HoodslyHub\OrderService\Client\Config\ClientConfig;

// Create configuration
$config = new ClientConfig([
    'api_key' => 'your-api-key',
    'base_url' => 'https://api.hoodslyhub.com/',
    'remote_domain' => 'your-domain.com'
]);

// Create client
$client = OrderClient::make($config);

// Create an order
$orderData = [
    'customer_name' => 'John Doe',
    'items' => [
        ['name' => 'Product 1', 'quantity' => 2, 'price' => 29.99]
    ]
];

$result = $client->createOrder($orderData);

if ($result['success']) {
    echo "Order created: " . $result['data']['order_id'];
} else {
    echo "Error: " . $result['error'];
}

Advanced Caching

The client includes powerful caching capabilities for optimal performance:

use HoodslyHub\OrderService\Client\OrderClient;
use HoodslyHub\OrderService\Client\Config\ClientConfig;
use HoodslyHub\OrderService\Client\Cache\FilesystemCache;

// Setup filesystem cache
$cache = new FilesystemCache('/tmp/hoodslyhub_cache', 'order_client_', 3600);

$config = new ClientConfig([
    'api_key' => 'your-api-key',
    'base_url' => 'https://api.hoodslyhub.com/',
    'remote_domain' => 'your-domain.com',
    'cache' => $cache,
    'cache_config' => [
        'token_ttl' => 3600,           // Token cache: 1 hour
        'order_ttl' => 300,            // Order cache: 5 minutes  
        'orders_list_ttl' => 60,       // Orders list: 1 minute
        'enable_response_cache' => true, // Enable response caching
        'cache_get_requests' => true,   // Cache GET requests
    ]
]);

$client = OrderClient::make($config);

// Cache management
$client->warmUpCache();         // Pre-populate cache
$client->clearCache();          // Clear all cache
$stats = $client->getCacheStats(); // Get cache statistics

Available Cache Adapters

Filesystem Cache (recommended for most applications):

use HoodslyHub\OrderService\Client\Cache\FilesystemCache;
$cache = new FilesystemCache('/path/to/cache', 'prefix_', 3600);

Redis Cache (for high-performance applications):

use HoodslyHub\OrderService\Client\Cache\RedisCache;
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cache = new RedisCache($redis, 'hoodslyhub:', 3600);

WordPress Cache (for WordPress integration):

use HoodslyHub\OrderService\Client\Cache\WordPressCache;
$cache = new WordPressCache('hoodslyhub_');

With Logging

use HoodslyHub\OrderService\Client\OrderClient;
use HoodslyHub\OrderService\Client\Config\ClientConfig;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Setup logger
$logger = new Logger('order-client');
$logger->pushHandler(new StreamHandler('path/to/your.log', Logger::INFO));

$config = new ClientConfig([
    'api_key' => 'your-api-key',
    'base_url' => 'https://api.hoodslyhub.com/',
    'logger' => $logger
]);

$client = OrderClient::make($config);

API Methods

Orders

  • createOrder(array $orderData): array - Create a new order
  • updateOrder(array $orderData, string $orderId): array - Update an existing order
  • getOrder(string $orderId): array - Get order details
  • getOrders(): array - Get list of orders
  • deleteOrder(string $orderId): array - Delete an order

Authentication

  • refreshToken(): bool - Manually refresh the access token using auth/refresh endpoint
  • hasValidToken(): bool - Check if the current token is valid

Refresh Token Functionality

The client now uses an optimized token refresh mechanism:

// Automatic token refresh on 401 responses
$orders = $client->getOrders(); // Automatically refreshes token if expired

// Manual token refresh
if ($client->refreshToken()) {
    echo "Token refreshed successfully";
}

// Check token validity
if ($client->hasValidToken()) {
    echo "Token is valid";
}

How it works:

  1. Automatic Refresh: When a request receives a 401 response, the client automatically calls the auth/refresh endpoint
  2. Optimized Endpoint: Uses POST /auth/refresh with the current token as Bearer authorization
  3. Dynamic TTL: Respects the expires_in field from the API response
  4. Fallback: If refresh fails, automatically falls back to full authentication
  5. Seamless: Original request is retried after successful token refresh

Benefits:

  • ⚡ Faster token renewal (no API key transmission)
  • 🔒 Enhanced security (reduced API key exposure)
  • 🔄 Automatic retry on authentication failures
  • 📊 Better performance with longer token lifetimes

Configuration Options

Option Type Default Description
api_key string required Your API key
base_url string required Base URL of the API
remote_domain string required Your domain name
timeout int 30 Request timeout in seconds
token_cache_duration int 3600 Token cache duration in seconds
cache CacheInterface null PSR-16 cache implementation
logger LoggerInterface null PSR-3 logger implementation

Error Handling

All methods return an array with the following structure:

[
    'success' => bool,
    'status_code' => int,
    'data' => array|null,
    'error' => string|null
]

Framework Integration

Laravel

// In a service provider
$this->app->singleton(OrderClient::class, function ($app) {
    $config = new ClientConfig([
        'api_key' => config('services.hoodslyhub.api_key'),
        'base_url' => config('services.hoodslyhub.base_url'),
        'remote_domain' => config('services.hoodslyhub.remote_domain'),
        'cache' => $app->make('cache.store'),
        'logger' => $app->make('log')
    ]);
    
    return OrderClient::make($config);
});

Symfony

# services.yaml
services:
    HoodslyHub\OrderService\Client\OrderClient:
        arguments:
            $config: '@HoodslyHub\OrderService\Client\Config\ClientConfig'
            $auth: '@HoodslyHub\OrderService\Client\Auth\AuthenticationManager'
    
    HoodslyHub\OrderService\Client\Config\ClientConfig:
        arguments:
            $options:
                api_key: '%env(HOODSLYHUB_API_KEY)%'
                base_url: '%env(HOODSLYHUB_BASE_URL)%'
                remote_domain: '%env(HOODSLYHUB_REMOTE_DOMAIN)%'
                cache: '@cache.app'
                logger: '@logger'

WordPress

// In your plugin or theme
use HoodslyHub\OrderService\Client\OrderClient;
use HoodslyHub\OrderService\Client\Config\ClientConfig;
use HoodslyHub\OrderService\Client\Cache\WordPressCache;

$config = new ClientConfig([
    'api_key' => get_option('hoodslyhub_api_key'),
    'base_url' => get_option('hoodslyhub_base_url'),
    'remote_domain' => get_site_url(),
    'cache' => new WordPressCache()
]);

$client = OrderClient::make($config);

License

MIT License. See LICENSE file for details.

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-03