bardan-io/temp-media-for-laravel
Composer 安装命令:
composer require bardan-io/temp-media-for-laravel
包简介
Laravel package for handling temporary media uploads with automatic cleanup
README 文档
README
A Laravel package for handling temporary media uploads with automatic cleanup, built on top of Spatie Media Library.
Features
- ✅ Two-Phase Upload Pattern - Upload images first, associate with models later
- ✅ Automatic Cleanup - TTL-based expiration and background cleanup jobs
- ✅ Security - Session/user-based ownership validation
- ✅ Type Safety - Full PHP 8.2+ type declarations with strict types
- ✅ Events - Comprehensive event system for monitoring and logging
- ✅ Testing - Complete test suite with factories and feature tests
- ✅ Configurable - Extensive configuration options
- ✅ Production Ready - Built with SOLID principles and clean architecture
Installation
You can install the package via composer:
composer require bardan-io/temp-media-for-laravel
Publish and run the migrations:
php artisan vendor:publish --tag="temp-media-migrations"
php artisan migrate
Optionally, you can publish the config file:
php artisan vendor:publish --tag="temp-media-config"
Usage
Basic Upload Flow
// 1. Upload images individually $uploadResponse = app(TempMediaServiceInterface::class)->uploadTempMedia( $uploadedFile, session()->getId(), auth()->id() ); // 2. Create a product with temp media IDs $product = Product::create([ 'name' => 'My Product', 'description' => 'Product description', // ... other fields ]); // 3. Transfer temp media to product $transferResult = $product->transferTempMedia(['temp-media-uuid-1', 'temp-media-uuid-2']);
Using the Trait
Add the HandlesTempMedia trait to your models:
use BardanIO\TempMedia\Traits\HandlesTempMedia; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; class Product extends Model implements HasMedia { use InteractsWithMedia; use HandlesTempMedia; // Transfer temp media to default collection public function attachTempImages(array $tempMediaIds) { return $this->transferTempMedia($tempMediaIds, 'product_images'); } }
API Endpoints
The package automatically registers these API routes:
POST /api/temp-media # Upload file GET /api/temp-media # List temp media GET /api/temp-media/{id} # Get temp media details DELETE /api/temp-media/{id} # Delete temp media POST /api/temp-media/validate # Validate temp media IDs
Frontend Integration
// Upload file const formData = new FormData(); formData.append('file', file); formData.append('session_id', sessionId); const response = await fetch('/api/temp-media', { method: 'POST', body: formData, headers: { 'X-CSRF-TOKEN': csrfToken } }); const result = await response.json(); // result.data contains: { id, url, thumb_url, original_name, expires_at } // Create product with temp media const productData = { name: 'Product Name', temp_media_ids: [result.data.id] }; await fetch('/api/products', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken }, body: JSON.stringify(productData) });
Configuration
return [ // TTL for temporary files (hours) 'default_ttl_hours' => 24, // Maximum file size in bytes 'max_file_size' => 10 * 1024 * 1024, // 10MB // Allowed MIME types 'allowed_mime_types' => [ 'image/jpeg', 'image/png', 'image/webp', 'image/gif', ], // Storage disk 'disk' => 'public', // Enable automatic cleanup 'enable_auto_cleanup' => true, // Route configuration 'routes' => [ 'prefix' => 'api/temp-media', 'middleware' => ['api'], ], // Rate limiting 'rate_limiting' => [ 'enabled' => true, 'max_attempts' => 60, 'decay_minutes' => 1, ], ];
Commands
Cleanup Expired Media
# Manual cleanup php artisan temp-media:cleanup # The package automatically registers this to run hourly
Events
The package dispatches several events you can listen to:
// Listen for uploads Event::listen(TempMediaUploaded::class, function ($event) { Log::info('Temp media uploaded', [ 'id' => $event->tempMedia->id, 'user' => $event->uploadDto->userId, ]); }); // Listen for transfers Event::listen(MediaTransferred::class, function ($event) { Log::info('Media transferred', [ 'model' => get_class($event->targetModel), 'count' => $event->transferDto->transferredCount, ]); });
Testing
composer test
Security
- UUID-based media IDs prevent enumeration
- Session/user ownership validation
- File type and size validation
- Rate limiting on upload endpoints
- Automatic cleanup prevents storage bloat
Architecture
The package follows clean architecture principles:
- Services - Business logic layer
- DTOs - Data transfer objects for type safety
- Contracts - Interfaces for dependency injection
- Events - Domain events for extensibility
- Traits - Reusable functionality for models
Contributing
Please see CONTRIBUTING for details.
License
The MIT License (MIT). Please see License File for more information.
bardan-io/temp-media-for-laravel 适用场景与选型建议
bardan-io/temp-media-for-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 434 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 10 月 08 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「package」 「media」 「upload」 「temporary」 「laravel」 「spatie」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 bardan-io/temp-media-for-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 bardan-io/temp-media-for-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 bardan-io/temp-media-for-laravel 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
The file manager intended for using Laravel with CKEditor / TinyMCE / Colorbox
Simple Sharing generates social media share links within CP entry pages, allowing you to quickly & easily share entries.
Laravel Media Popup to upload/view the files
Simple ASCII output of array data
Asset Manager Laravel package for Gigcodes UI Library
统计信息
- 总下载量: 434
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 20
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-08