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

dahovitech/media-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dahovitech/media-bundle
    

    Add to config/bundles.php:

    DahoviTech\MediaBundle\DahoviTechMediaBundle::class => ['all' => true],
    
  2. Configure Dependencies: Update vich_uploader.yaml, liip_imagine.yaml, and oneup_flysystem.yaml as per the README.

  3. Database Setup:

    php bin/console doctrine:schema:update --force
    
  4. First Use Case: Upload a file via the API:

    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    fetch('/api/media/upload', { method: 'POST', body: formData })
      .then(response => response.json())
      .then(media => console.log(media));
    

Implementation Patterns

Common Workflows

1. File Upload in Controllers

Use the MediaManager service for programmatic uploads:

use DahoviTech\MediaBundle\Service\MediaManager;

public function upload(UploadedFile $file, MediaManager $mediaManager)
{
    $media = $mediaManager->createFromUploadedFile(
        $file,
        'Image Title',
        'Description',
        true // public
    );
    return $this->json($media);
}

2. Image Transformation

Leverage LiipImagineBundle configurations for dynamic thumbnails:

# config/packages/liip_imagine.yaml
liip_imagine:
    filter_sets:
        custom_thumb:
            filters:
                thumbnail: { size: [200, 200], mode: outbound }

Access via API:

fetch(`/api/media/${id}/thumbnail?filter=custom_thumb`)

3. Storage Abstraction

Switch between local/S3/GCS by updating config:

# config/packages/dahovi_tech_media.yaml
dahovi_tech_media:
    storage:
        adapter: s3  # or 'gcs'
        s3:
            bucket: 'your-bucket'

4. API Integration

Use API endpoints for frontend uploads (e.g., TinyMCE):

tinymce.init({
    images_upload_url: '/api/media/upload',
    images_upload_handler: (blobInfo, success) => {
        const formData = new FormData();
        formData.append('file', blobInfo.blob());
        fetch('/api/media/upload', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(media => success(media.url));
    }
});

5. CLI Automation

Run batch operations:

# Generate thumbnails for all images
php bin/console dahovi-tech:media:generate-thumbnails

# Clean expired media
php bin/console dahovi-tech:media:cleanup-expired

Gotchas and Tips

Pitfalls

  1. MIME Type Validation:

    • Strict validation may reject files even with correct extensions. Verify mime_types in config:
      dahovi_tech_media:
          security:
              mime_types:
                  - 'image/jpeg'
                  - 'application/pdf'
      
  2. File Size Limits:

    • PHP post_max_size and upload_max_filesize must exceed max_file_size in config.
  3. CDN Configuration:

    • If cdn.enabled: true, ensure cdn.url points to the correct CDN endpoint. Test with:
      curl -I "https://your-cdn.com/uploads/media/filename.jpg"
      
  4. Doctrine Events:

    • Override media lifecycle events (e.g., prePersist) via:
      // src/EventSubscriber/MediaSubscriber.php
      use DahoviTech\MediaBundle\Entity\Media;
      use Doctrine\Common\EventSubscriber;
      
      class MediaSubscriber implements EventSubscriber
      {
          public function getSubscribedEvents()
          {
              return [Media::PRE_PERSIST];
          }
      
          public function prePersist(Media $media)
          {
              $media->setName('Default_' . $media->getName());
          }
      }
      

Debugging Tips

  1. Check Upload Paths:

    • Verify upload_destination in vich_uploader.yaml matches upload_path in dahovi_tech_media.yaml.
  2. Log FilePond Errors:

    • Enable debug mode to capture FilePond validation errors:
      FilePond.registerPlugin(FilePondPluginImagePreview);
      FilePond.setOptions({
          server: {
              process: (fieldName, file, metadata, load, error) => {
                  console.log('Uploading:', file.name);
                  // Handle errors
                  error('Error message');
              }
          }
      });
      
  3. Thumbnail Generation:

    • Force regenerate thumbnails with:
      php bin/console dahovi-tech:media:generate-thumbnails --force
      
  4. API Rate Limiting:

    • If using Symfony’s rate limiter, configure in api_platform.yaml:
      api_platform:
          formats:
              jsonld:
                  mime_types: ['application/ld+json']
          patch_formats:
              json: ['application/merge-patch+json']
          swagger:
              versions: [3]
      

Extension Points

  1. Custom Filters: Add new LiipImagine filters in liip_imagine.yaml:

    filter_sets:
        custom_filter:
            filters:
                resize: { width: 300, height: 300 }
                watermark: { image: 'path/to/watermark.png' }
    
  2. Event Listeners: Extend media behavior via Doctrine events:

    // src/EventListener/MediaListener.php
    use DahoviTech\MediaBundle\Entity\Media;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class MediaListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [Media::PRE_REMOVE];
        }
    
        public function preRemove(Media $media)
        {
            if (!$media->isPublic()) {
                throw new \RuntimeException('Cannot delete private media');
            }
        }
    }
    
  3. Custom Storage Adapters: Implement Oneup\FlysystemBundle\Model\StorageInterface for new backends (e.g., Azure Blob Storage).

  4. Admin Panel Customization: Override Twig templates in templates/bundles/dahovitechmedia/ to modify the admin UI.

Performance Optimizations

  1. Cache Headers: Configure CDN cache headers in oneup_flysystem.yaml:

    oneup_flysystem:
        filesystems:
            media_filesystem:
                adapter: s3_adapter
                options:
                    cache_control: 'public, max-age=31536000'
    
  2. Lazy Loading: Use ApiPlatform\Metadata\ApiResource to lazy-load media in API responses:

    #[ApiResource(
        collectionOperations: ['get' => ['pagination_items_per_page' => 50]],
        itemOperations: ['get' => ['method' => 'GET']]
    )]
    class Media {}
    
  3. Batch Processing: Process large media collections in chunks:

    use DahoviTech\MediaBundle\Repository\MediaRepository;
    
    $mediaRepo = $this->getDoctrine()->getRepository(Media::class);
    $medias = $mediaRepo->findBy([], [], 100); // 100 items per batch
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime