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
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
- Installation
- Usage
- Advanced Features
- Configuration Reference
- Testing
- Migration Guide
- Troubleshooting
Quick Start
-
Install the package:
composer require cleaniquecoders/laravel-api-version
-
Publish configuration:
php artisan vendor:publish --tag="laravel-api-version-config" -
Set up routes with versioning:
Route::middleware(['api', 'api.version'])->group(function () { Route::get('/users', 'UserController@index'); });
-
Create versioned controllers:
app/Http/Controllers/Api/V1/UserController.php app/Http/Controllers/Api/V2/UserController.php -
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-Versionand 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:v1directs routes in the group to thev1namespace.api.version:v2directs routes to thev2namespace, 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 versioningv1.1,v2.5- Minor versionsv1.0.1- Patch versions- Automatic normalization (e.g.,
1becomesv1)
Controller Namespace Mapping
Versions are automatically mapped to controller namespaces:
v1→App\Http\Controllers\Api\V1v2.1→App\Http\Controllers\Api\V2_1v3.0.1→App\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:
- Add version validation by configuring
supported_versions - Set up deprecation warnings using
deprecated_versions - Update error handling to catch
InvalidApiVersionException - 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_versionis included insupported_versionswhen specified - Verify regex patterns in
accept_header_patternare valid - Check that
root_namespacepoints to existing namespace
Performance considerations:
- Use
supported_versionsto 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 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 cleaniquecoders/laravel-api-version 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Provide organization related app
Spatie Media Library Manager
Alfabank REST API integration
AppPulse provide a comprehensive, easy-to-use monitoring tool with uptime tracking, SSL certificate checks, and customisable notifications.
Define, sign, dispatch and log outgoing webhooks in Laravel with retries, HMAC signatures, and an optional Livewire + Flux admin UI.
Audit Database Schema Design
统计信息
- 总下载量: 1.03k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-11-03