cleaniquecoders/laravel-api-version 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

cleaniquecoders/laravel-api-version

Composer 安装命令:

composer require cleaniquecoders/laravel-api-version

包简介

Effortlessly manage your Laravel API versions with flexible, header-based versioning control.

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status PHPStan Total Downloads

Laravel API Version

Effortlessly manage your Laravel API versions with flexible, header-based versioning control, comprehensive validation, deprecation management, and enterprise-ready features.

Features

Header-based Version Detection - Automatic version resolution from Accept or custom headers 🛡️ Comprehensive Validation - Boot-time configuration validation and runtime version validation 📅 Deprecation Management - Built-in support for API version deprecation with proper HTTP headers ⚡ Performance Optimized - Caching for namespace resolution and configuration 🎯 Explicit Version Control - Support for both automatic detection and explicit version specification 🔧 Enterprise Ready - Production-quality error handling and monitoring capabilities

Table of Contents

Quick Start

  1. Install the package:

    composer require cleaniquecoders/laravel-api-version
  2. Publish configuration:

    php artisan vendor:publish --tag="laravel-api-version-config"
  3. Set up routes with versioning:

    Route::middleware(['api', 'api.version'])->group(function () {
        Route::get('/users', 'UserController@index');
    });
  4. Create versioned controllers:

    app/Http/Controllers/Api/V1/UserController.php
    app/Http/Controllers/Api/V2/UserController.php
    
  5. Make requests with version headers:

    curl -H "X-API-Version: 2" https://yourapp/api/users

Installation

You can install the package via composer:

composer require cleaniquecoders/laravel-api-version

You can publish the config file with:

php artisan vendor:publish --tag="laravel-api-version-config"

Usage

Configuration

This will create a config/api-version.php file where you can customize options like the default version, headers, version format, supported versions, deprecation settings, and the root namespace for versioned controllers.

Example configuration:

return [
    // Basic Configuration
    'default_version' => 'v1',
    'use_accept_header' => true,
    'custom_header' => 'X-API-Version',
    'accept_header_pattern' => '/application\/vnd\.\w+\+v(\d+(\.\d+)*)\+json/',
    'root_namespace' => 'App\Http\Controllers\Api',

    // Version Management
    'supported_versions' => [
        'v1', 'v2', 'v3'
    ],

    // Deprecation Management
    'deprecated_versions' => [
        'v1' => [
            'sunset_date' => '2024-12-31',
            'replacement' => 'v2',
            'message' => 'API v1 is deprecated. Please migrate to v2.',
        ],
    ],
];

Key Configuration Options

  • supported_versions - Whitelist of allowed API versions (empty array allows all)
  • deprecated_versions - Configure deprecation warnings with sunset dates and replacement versions
  • Version validation - Automatic validation of version formats and supported versions
  • Performance caching - Built-in caching for namespace resolution and configuration

Middleware Setup

The api.version middleware is registered automatically. This middleware provides:

  • 🔍 Automatic version detection from headers or explicit specification
  • Comprehensive validation with helpful error messages
  • 📊 Response headers including X-API-Version and deprecation warnings
  • 🚀 Performance optimization through caching

Defining Versioned Routes

Option 1: Header-Based Version Detection

To enable automatic version detection from headers, use the api.version middleware in your routes/api.php:

use Illuminate\Support\Facades\Route;

Route::middleware(['api', 'api.version'])->group(function () {
    Route::get('/example', 'ExampleController@index');
    // Additional routes here
});

This setup detects versions from the Accept or X-API-Version headers, dynamically routing requests to the correct versioned namespace.

Option 2: Explicitly Setting the Version

You can explicitly define a version for a route or route group by passing the version to the middleware. This approach bypasses header detection.

use Illuminate\Support\Facades\Route;

Route::middleware(['api', 'api.version:v1'])->group(function () {
    Route::get('/example', 'ExampleController@index');
    // Routes for v1
});

Route::middleware(['api', 'api.version:v2'])->group(function () {
    Route::get('/example', 'ExampleController@index');
    // Routes for v2
});

In this example:

  • api.version:v1 directs routes in the group to the v1 namespace.
  • api.version:v2 directs routes to the v2 namespace, ignoring headers.

Example Requests

Using Accept Header

curl -L -H "Accept: application/vnd.yourapp+v2+json" https://yourapp/api/example

Using Custom Header (X-API-Version)

curl -L -H "X-API-Version: 2" https://yourapp/api/example

Explicitly Versioned Route

If the route is explicitly defined as api.version:v2, no header is needed to access version 2.

Advanced Features

Version Validation

The package provides comprehensive version validation:

// Automatically validates version format (v1, v2, v1.1, etc.)
// Checks against supported_versions if configured
// Provides clear error messages for invalid versions

// Example error response for invalid version:
{
    "error": "Invalid API version",
    "message": "Unsupported API version: 'v5'. Supported versions: v1, v2, v3",
    "supported_versions": ["v1", "v2", "v3"]
}

Deprecation Management

When using deprecated versions, the API automatically adds appropriate headers:

HTTP/1.1 200 OK
X-API-Version: v1
Deprecation: true
Sunset: 2024-12-31
Link: <https://api.example.com/v2>; rel="successor-version"
X-API-Deprecation-Message: API v1 is deprecated. Please migrate to v2.

Version Format Support

The package supports various version formats:

  • v1, v2, v3 - Simple versioning
  • v1.1, v2.5 - Minor versions
  • v1.0.1 - Patch versions
  • Automatic normalization (e.g., 1 becomes v1)

Controller Namespace Mapping

Versions are automatically mapped to controller namespaces:

  • v1App\Http\Controllers\Api\V1
  • v2.1App\Http\Controllers\Api\V2_1
  • v3.0.1App\Http\Controllers\Api\V3_0_1

Performance Optimizations

  • Configuration Caching - Reduces repeated config() calls
  • 🗄️ Namespace Caching - Caches namespace resolution results
  • 🔄 Cache Management - Automatic cache invalidation and testing support

Error Handling

The package provides robust error handling:

  • Configuration Validation - Validates config at boot time
  • Runtime Validation - Validates versions during request processing
  • Clear Error Messages - Helpful error responses for debugging
  • Exception Types - Custom exceptions for different error scenarios

Configuration Reference

Complete Configuration Example

return [
    // Required: Default version when none specified
    'default_version' => 'v1',

    // Header Configuration
    'use_accept_header' => true,
    'custom_header' => 'X-API-Version',
    'accept_header_pattern' => '/application\/vnd\.\w+\+v(\d+(\.\d+)*)\+json/',

    // Namespace Configuration
    'root_namespace' => 'App\Http\Controllers\Api',

    // Version Management
    'supported_versions' => [
        'v1', 'v2', 'v3'
    ],

    // Deprecation Configuration
    'deprecated_versions' => [
        'v1' => [
            'sunset_date' => '2024-12-31',        // RFC 7234 Sunset header
            'replacement' => 'v2',                // Replacement version
            'message' => 'API v1 is deprecated.', // Custom message
        ],
        'v2' => [
            'sunset_date' => '2025-06-30',
            'replacement' => 'v3',
            'message' => 'API v2 will be sunset on June 30, 2025.',
        ],
    ],
];

Testing

Run the package tests:

composer test

Run with coverage:

composer test-coverage

Run static analysis:

composer analyse

The package includes comprehensive tests covering:

  • ✅ Version resolution and validation
  • ✅ Configuration validation
  • ✅ Deprecation functionality
  • ✅ Performance optimizations
  • ✅ Error handling scenarios
  • ✅ Middleware integration

Migration Guide

From v1.x to v2.x

The package maintains backward compatibility, but you can take advantage of new features:

  1. Add version validation by configuring supported_versions
  2. Set up deprecation warnings using deprecated_versions
  3. Update error handling to catch InvalidApiVersionException
  4. Review performance improvements with built-in caching

Upgrading Controllers

No changes required to existing controllers. The enhanced namespace mapping automatically handles:

// v1 controllers remain in: App\Http\Controllers\Api\V1
// v2.1 controllers work in: App\Http\Controllers\Api\V2_1

Troubleshooting

Common Issues

Invalid version format errors:

// ❌ Wrong
'supported_versions' => ['1', '2', 'invalid']

// ✅ Correct
'supported_versions' => ['v1', 'v2', 'v3']

Configuration validation errors:

  • Ensure default_version is included in supported_versions when specified
  • Verify regex patterns in accept_header_pattern are valid
  • Check that root_namespace points to existing namespace

Performance considerations:

  • Use supported_versions to limit valid versions
  • Configure appropriate cache TTL for your environment
  • Monitor deprecation header overhead for high-traffic APIs

Changelog

Please see CHANGELOG for details on recent updates.

Contributing

Please see CONTRIBUTING for contribution guidelines.

Security Vulnerabilities

Please review our security policy for reporting security issues.

Credits

License

The MIT License (MIT). See the License File for details.

cleaniquecoders/laravel-api-version 适用场景与选型建议

cleaniquecoders/laravel-api-version 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.03k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2024 年 11 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 cleaniquecoders/laravel-api-version 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-11-03