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

apoutchika/media-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require apoutchika/media-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Apoutchika\MediaBundle\ApoutchikaMediaBundle::class => ['all' => true],
    ];
    
  2. Configure Storage (config/packages/apoutchika_media.yaml):

    apoutchika_media:
        db_driver: doctrine_orm
        gaufrette:
            adapter: local
            filesystem: '%kernel.project_dir%/public/uploads'
    
  3. Create a Media Entity:

    php bin/console make:entity Media
    

    Add Media trait to your entity:

    use Apoutchika\MediaBundle\Entity\MediaTrait;
    
    class YourEntity
    {
        use MediaTrait;
    }
    
  4. First Use Case: Add a media field to a form:

    $builder->add('media', 'apoutchika_media', [
        'context' => 'user:1', // Restrict access
        'allowed_types' => ['image/jpeg', 'image/png'],
        'allowed_mime_types' => ['image/*'],
        'max_size' => 2048, // KB
    ]);
    

Implementation Patterns

Common Workflows

1. Uploading & Managing Media

  • Form Integration:

    // In a controller
    $form = $this->createFormBuilder($entity)
        ->add('media', 'apoutchika_media', [
            'label' => 'Profile Image',
            'context' => 'user:'.$userId,
            'allowed_types' => ['image/jpeg', 'image/png'],
            'max_width' => 1024,
            'max_height' => 1024,
        ])
        ->getForm();
    
  • Handling Uploads:

    // After form submission
    $media = $entity->getMedia();
    if ($media) {
        $media->setContext('user:'.$userId); // Update context if needed
        $media->setFocus(50, 50); // Set focus point (x, y)
    }
    

2. Rendering Media

  • Twig Usage:

    {% render_media media, 'thumb' %}
    

    Define a thumb filter in config/packages/apoutchika_media.yaml:

    apoutchika_media:
        filters:
            thumb:
                filter: thumbnail
                options:
                    size: [200, 200]
                    mode: outbound
    
  • Dynamic Filters:

    // In a controller
    return $this->render('media/show.html.twig', [
        'media' => $media,
        'filter' => 'thumb', // Pass dynamically
    ]);
    

3. Context-Based Access

  • Restrict Media by Context:
    # config/packages/apoutchika_media.yaml
    apoutchika_media:
        contexts:
            - 'user:*'       # User-specific media
            - 'document:*'   # Document-specific media
    
    // In form options
    'context' => 'document:'.$documentId
    

4. CKEditor Integration

  • Configure CKEditor:
    # config/packages/apoutchika_media.yaml
    apoutchika_media:
        ckeditor:
            enabled: true
            toolbar: [
                { name: 'document', items: ['Media'] },
            ]
    
    {{ render(controller('ApoutchikaMediaBundle:Media:ckeditor')) }}
    

5. Batch Processing

  • Resizing All Media:
    use Apoutchika\MediaBundle\Manager\MediaManager;
    
    $mediaManager = $this->container->get('apoutchika_media.manager.media');
    $media = $mediaManager->findBy(['context' => 'user:1']);
    foreach ($media as $item) {
        $item->applyFilter('thumb'); // Apply filter to all
        $mediaManager->persist($item);
    }
    

Gotchas and Tips

Pitfalls & Debugging

  1. Permission Issues:

    • Ensure the uploads directory is writable:
      chmod -R 775 %kernel.project_dir%/public/uploads
      
    • If using FTP, verify credentials in config/packages/apoutchika_media.yaml:
      gaufrette:
          adapter: ftp
          filesystem: 'ftp://user:pass@host/path'
      
  2. Focus Point Errors:

    • If setFocus() fails, ensure the image is loaded via applyFilter() first:
      $media->applyFilter('original'); // Ensure image is processed
      $media->setFocus(30, 40);
      
  3. Context Mismatches:

    • Double-check context strings (e.g., user:1 vs user:12). Typos here will cause 403 errors.
  4. Filter Caching:

    • Clear the cache after adding new filters:
      php bin/console cache:clear
      
  5. Doctrine Proxy Issues:

    • If media isn’t persisting, ensure your entity uses MediaTrait and the Media entity is properly mapped:
      /**
       * @ORM\OneToOne(targetEntity="Apoutchika\MediaBundle\Entity\Media", cascade={"persist", "remove"})
       */
      use MediaTrait;
      

Configuration Quirks

  1. Gaufrette Adapters:

    • For custom adapters (e.g., S3), extend Gaufrette\Adapter\AbstractAdapter and update config/packages/apoutchika_media.yaml:
      gaufrette:
          adapter: custom
          filesystem: 's3://bucket-name'
      
  2. MIME Type Restrictions:

    • Use allowed_mime_types for broader restrictions (e.g., ['image/*']) and allowed_types for specific types (e.g., ['image/jpeg']).
  3. IE8 Compatibility:

    • The bundle includes a fallback for IE8, but test thoroughly if supporting legacy browsers. Disable via:
      apoutchika_media:
          ie8_compatibility: false
      

Extension Points

  1. Custom Filters:

    • Create a custom filter by extending Apoutchika\MediaBundle\Filter\FilterInterface:
      namespace App\Media\Filter;
      
      use Apoutchika\MediaBundle\Filter\FilterInterface;
      use Imagine\Image\ImageInterface;
      
      class CustomFilter implements FilterInterface
      {
          public function apply(ImageInterface $image, array $options)
          {
              // Custom logic (e.g., grayscale)
              return $image->effects()->grayscale();
          }
      }
      
    • Register in config/packages/apoutchika_media.yaml:
      filters:
          custom:
              filter: App\Media\Filter\CustomFilter
              options: []
      
  2. Event Listeners:

    • Hook into media events (e.g., media.pre_upload):
      // src/EventListener/MediaListener.php
      use Apoutchika\MediaBundle\Event\MediaEvent;
      
      class MediaListener
      {
          public function onPreUpload(MediaEvent $event)
          {
              if ($event->getMedia()->getMimeType() === 'image/jpeg') {
                  $event->setAllowed(true);
              }
          }
      }
      
    • Register in services.yaml:
      services:
          App\EventListener\MediaListener:
              tags:
                  - { name: kernel.event_listener, event: apoutchika_media.pre_upload, method: onPreUpload }
      
  3. Overriding Templates:

    • Copy templates from vendor/apoutchika/media-bundle/Resources/views/ to templates/apoutchika_media/ to customize:
      • Media/ckeditor.html.twig
      • Media/fields.html.twig
      • Media/list.html.twig
  4. Doctrine Lifecycle Callbacks:

    • Use callbacks to auto-apply filters on entity flush:
      use Doctrine\ORM\Mapping as ORM;
      
      /**
       * @ORM\PrePersist
       * @ORM\PreUpdate
       */
      public function preUpload()
      {
          if ($this->getMedia()) {
              $this->getMedia()->applyFilter('thumb');
          }
      }
      

Performance Tips

  1. Lazy Loading:

    • Disable lazy loading for media if not needed:
      apoutchika_media:
          lazy_loading: false
      
  2. Batch Processing:

    • Use MediaManager to process media in bulk (e.g., during cron jobs):
      $mediaManager = $this->container->get('apoutchika_media.manager.media');
      $
      
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