Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Media Bundle Laravel Package

phpmob/media-bundle

Symfony bundle configuring media storage via a PHPCR-backed Flysystem filesystem. Provides ready-to-import YAML config and supports overriding the PHPCR UTF-8 connection parameter for media storage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require phpmob/media-bundle
    

    Publish the bundle’s configuration:

    php artisan vendor:publish --provider="PhpMob\MediaBundle\MediaBundle" --tag=config
    
  2. Configuration Update config/media.php to define storage paths (local, S3, etc.) and allowed file types:

    'disks' => [
        'local' => [
            'driver' => 'local',
            'root'   => storage_path('app/media'),
        ],
    ],
    'allowed_mimes' => ['image/jpeg', 'image/png', 'application/pdf'],
    
  3. First Use Case: Uploading a File Inject the MediaManager into a controller/service:

    use PhpMob\MediaBundle\Manager\MediaManager;
    
    public function upload(Request $request, MediaManager $mediaManager)
    {
        $file = $request->file('media');
        $media = $mediaManager->upload($file, [
            'disk' => 'local',
            'path' => 'user_uploads',
        ]);
        return response()->json($media);
    }
    
  4. Key Files to Review

    • config/media.php: Disk and validation rules.
    • src/Manager/MediaManager.php: Core upload logic.
    • src/Entity/Media.php: Media model structure.

Implementation Patterns

Core Workflows

  1. Uploading Media

    // Basic upload
    $media = $mediaManager->upload($file, ['disk' => 'local']);
    
    // With custom path and metadata
    $media = $mediaManager->upload($file, [
        'disk' => 's3',
        'path' => 'products/{year}',
        'metadata' => ['product_id' => 123],
    ]);
    
  2. Generating URLs

    $url = $mediaManager->getUrl($media, 'thumb'); // Uses named presets
    
  3. Deleting Media

    $mediaManager->delete($media); // Soft or hard delete based on config
    
  4. Batch Operations

    $mediaManager->deleteMultiple([$media1, $media2]); // Bulk delete
    

Integration Tips

  • Laravel Filesystem: Leverage Laravel’s built-in disk configuration (e.g., s3, ftp) for flexibility.
  • Events: Bind to media.uploaded or media.deleted events for post-processing:
    Event::listen('media.uploaded', function ($media) {
        // Example: Log uploads or trigger notifications
    });
    
  • Validation: Extend PhpMob\MediaBundle\Validator\MediaValidator to add custom rules.
  • Presets: Define image/video transformations in config/media.php under presets:
    'presets' => [
        'thumb' => [
            'width' => 200,
            'height' => 200,
            'fit' => 'crop',
        ],
    ],
    

Common Use Cases

Use Case Implementation Example
User Profile Avatars Upload to users/{user_id}/avatar with disk: 's3'.
Product Images Use presets (thumb, large) and store in products/{id}/images.
Document Management Validate MIME types (e.g., application/pdf) and restrict access via policies.
Video Thumbnails Generate thumbnails on upload using FFmpeg (if supported by the bundle).

Gotchas and Tips

Pitfalls

  1. Disk Configuration

    • Issue: Forgetting to define disks in config/media.php or Laravel’s filesystems.php.
    • Fix: Verify disks exist and are accessible:
      php artisan storage:link  # For local disk
      
    • Tip: Use php artisan vendor:publish --tag=media-config to reset defaults.
  2. File Validation

    • Issue: MIME type spoofing (e.g., .jpg files with malicious content).
    • Fix: Combine bundle validation with Laravel’s ValidatesWhen or custom rules:
      use PhpMob\MediaBundle\Rules\MimeType;
      
      $request->validate([
          'file' => ['required', new MimeType(['image/jpeg', 'image/png'])],
      ]);
      
  3. Path Conflicts

    • Issue: Overwriting files if paths aren’t unique (e.g., path: 'uploads').
    • Fix: Use UUIDs or timestamps in paths:
      $mediaManager->upload($file, [
          'path' => 'uploads/' . now()->format('Y/m/d'),
      ]);
      
  4. Event Listeners

    • Issue: Events not firing due to incorrect binding.
    • Fix: Register listeners in a service provider’s boot() method:
      public function boot()
      {
          Event::listen('media.uploaded', [MediaLogger::class, 'logUpload']);
      }
      
  5. Legacy Code

    • Issue: Bundle was last updated in 2019; may lack PHP 8+ or Laravel 9+ support.
    • Fix: Check for:
      • Type hints (add ? for nullable properties if needed).
      • Compatibility with Laravel’s service container (e.g., bindIf).
      • Deprecated methods (e.g., Str::slug()Str::of($str)->slug()).

Debugging Tips

  • Log Uploads: Temporarily add logging to MediaManager::upload():
    \Log::debug('Uploading to disk', ['disk' => $config['disk'], 'path' => $path]);
    
  • Check Disk Permissions: Ensure the storage directory is writable:
    chmod -R 775 storage/app/media
    
  • Validate Config: Use dd($mediaManager->getConfig()) to inspect active settings.

Extension Points

  1. Custom Storage Drivers

    • Extend PhpMob\MediaBundle\Storage\DriverInterface for custom backends (e.g., Google Cloud Storage).
  2. Model Bindings

    • Bind the Media model to Eloquent for ORM features:
      class Product extends Model
      {
          public function media()
          {
              return $this->morphMany(Media::class, 'model');
          }
      }
      
  3. API Responses

    • Normalize responses using Laravel’s Resource classes:
      class MediaResource extends JsonResource
      {
          public function toArray($request)
          {
              return [
                  'id' => $this->id,
                  'url' => $this->url,
                  'size' => $this->size,
                  'presets' => $this->presets,
              ];
          }
      }
      
  4. Queue Uploads

    • Dispatch uploads to a queue for large files:
      UploadJob::dispatch($file, $config)->onQueue('media');
      
      (Requires custom job class and queue configuration.)

Performance

  • Batch Processing: Use MediaManager::deleteMultiple() for bulk deletes.
  • Preset Caching: Generate and cache presets (e.g., thumbnails) during upload:
    $mediaManager->upload($file, [
        'generate_presets' => true,
    ]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky