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

darkanakin41/media-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require darkanakin41/media-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+):

    return [
        // ...
        Darkanakin41\MediaBundle\MediaBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config (Symfony 4+):

    php bin/console darkanakin41:media:install
    

    Update config/packages/darkanakin41_media.yaml to define:

    • upload_dir: Local storage path (e.g., uploads/media).
    • allowed_mimes: File types (e.g., ['image/jpeg', 'image/png']).
    • resize_options: Default dimensions (e.g., {'width': 800, 'height': 600}).
  3. First Upload Use the MediaUploader service in a controller:

    use Darkanakin41\MediaBundle\Service\MediaUploader;
    
    public function upload(Request $request, MediaUploader $uploader)
    {
        $file = $request->file('media');
        $path = $uploader->upload($file, 'user_uploads');
        return response()->json(['path' => $path]);
    }
    

Implementation Patterns

Core Workflows

  1. File Uploads

    • Single File:
      $path = $uploader->upload($request->file('image'), 'category_x');
      
    • Multiple Files:
      $paths = $uploader->uploadMultiple($request->file('images'), 'gallery');
      
  2. Image Resizing Integrate with MediaResizer:

    $resizer = $this->container->get('darkanakin41_media.resizer');
    $resizedPath = $resizer->resize($originalPath, ['width' => 400]);
    
  3. Validation Use the MediaValidator to check file types/sizes:

    $validator = $this->container->get('darkanakin41_media.validator');
    if (!$validator->isAllowed($file)) {
        throw new \Exception('Invalid file type.');
    }
    

Integration Tips

  • Symfony Forms: Add a FileType field and validate with MediaValidator in a custom constraint.

    $builder->add('media', FileType::class, [
        'constraints' => [new MediaConstraint($validator)],
    ]);
    
  • Storage Abstraction: Extend the StorageInterface to support cloud storage (e.g., S3) by implementing:

    class S3Storage implements StorageInterface {
        public function save($file, $path) { /* ... */ }
        public function getUrl($path) { /* ... */ }
    }
    

    Register it in services.yaml:

    services:
        Darkanakin41\MediaBundle\Service\StorageInterface: '@app.s3_storage'
    
  • Event Listeners: Trigger actions post-upload (e.g., generate thumbnails):

    use Darkanakin41\MediaBundle\Event\MediaUploadedEvent;
    
    public function onMediaUploaded(MediaUploadedEvent $event)
    {
        $resizer->resize($event->getPath(), ['width' => 150]);
    }
    

    Bind in services.yaml:

    services:
        App\Listener\ThumbnailListener:
            tags:
                - { name: kernel.event_listener, event: media.uploaded, method: onMediaUploaded }
    

Gotchas and Tips

Pitfalls

  1. No Documentation

    • The package lacks formal docs. Reverse-engineer usage from:
      • src/Service/MediaUploader.php (core logic).
      • tests/ (basic examples).
    • Example: Resize options are passed as an array, but the exact keys (width, height, quality) must match the internal ResizeOptions class.
  2. Light Testing

    • Edge cases (e.g., corrupt files, large uploads) may fail silently. Add custom validation:
      if ($file->getSize() > 10_000_000) { // 10MB
          throw new \RuntimeException('File too large.');
      }
      
  3. Hardcoded Paths

    • The upload_dir config uses relative paths. Ensure the directory exists:
      mkdir -p uploads/media
      chmod -R 775 uploads/media
      
  4. No Database Integration

    • The bundle doesn’t track metadata (e.g., filenames, upload dates). Manually log to a DB or use a trait:
      use Darkanakin41\MediaBundle\Traits\MediaLogger;
      
      class UserMedia {
          use MediaLogger;
          protected $table = 'user_media';
      }
      

Debugging

  • Failed Uploads: Check var/log/dev.log for MediaException. Common causes:

    • Missing upload_dir permission.
    • Invalid MIME type (verify allowed_mimes in config).
    • PHP upload_max_filesize limits.
  • Resize Issues: Ensure gd or imagick PHP extensions are installed:

    php -m | grep -E 'gd|imagick'
    

Extension Points

  1. Custom Storage Override StorageInterface to support:

    • Local paths (LocalStorage).
    • Cloud storage (S3, GCS) via Flysystem adapter.
  2. Post-Processing Extend MediaUploader to auto-generate variants:

    class ExtendedUploader extends MediaUploader {
        protected function postUpload($path) {
            $this->resizer->resize($path, ['width' => 300]); // Thumbnail
            $this->resizer->resize($path, ['width' => 1200]); // Large
        }
    }
    

    Bind in services.yaml:

    services:
        Darkanakin41\MediaBundle\Service\MediaUploader: '@app.extended_uploader'
    
  3. Security Sanitize filenames to prevent path traversal:

    $safeName = preg_replace('/[^a-z0-9._-]/i', '_', $file->getClientOriginalName());
    $uploader->upload($file, 'safe_dir', $safeName);
    
  4. Symfony Messenger Decouple uploads from HTTP requests by dispatching a MediaUploadMessage:

    use Darkanakin41\MediaBundle\Message\MediaUploadMessage;
    
    $bus->dispatch(new MediaUploadMessage($file, 'async_dir'));
    

    Configure the handler in config/packages/messenger.yaml:

    frameworks:
        messenger:
            transports:
                async: '%env(MESSENGER_TRANSPORT_DSN)%'
            routing:
                'Darkanakin41\MediaBundle\Message\MediaUploadMessage': async
    

Configuration Quirks

  • Resize Quality: Default quality is 75. Override in config:

    resize_options:
        quality: 90
    
  • Case-Sensitive MIME Checks: Ensure allowed_mimes matches exact MIME strings (e.g., image/jpeg vs. JPEG).

  • No Auto-Cleanup: Deleted files aren’t purged. Implement a cron job:

    php bin/console darkanakin41:media:cleanup --dir=uploads/media --dry-run
    

    (Note: Command may not exist; check src/Command/ for available commands.)

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui