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

Mediabundle Laravel Package

alpixel/mediabundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alpixel/mediabundle:~2.0
    

    Ensure your composer.json includes liip/imagine-bundle (required dependency).

  2. Register the Bundle: Add to app/AppKernel.php:

    new Alpixel\Bundle\MediaBundle\AlpixelMediaBundle(),
    
  3. Configure Uploads: Update config.yml:

    alpixel_media:
        upload_folder: "%kernel.root_dir%/../web/upload/"
        allowed_mimetypes: ['image/*', 'application/pdf']
    
  4. Enable Routing: Include in app/config/routing.yml:

    alpixel_media:
        resource: '@AlpixelMediaBundle/Resources/config/routing.yml'
    
  5. Twig Setup: Add Twig resources:

    twig:
        form:
            resources: ['AlpixelMediaBundle:Form:fields.html.twig']
    
  6. Update Database: Run:

    php app/console doctrine:schema:update --force
    

First Use Case: Uploading Media

  1. Create a Form Type: Extend AlpixelMediaBundle\Form\Type\MediaType or use it directly in your form:

    $builder->add('media', 'alpixel_media', [
        'label' => 'Upload Media',
        'mapped' => false,
    ]);
    
  2. Handle Upload in Controller:

    $media = new \Alpixel\Bundle\MediaBundle\Entity\Media();
    $media->setFile($request->files->get('media'));
    $em->persist($media);
    $em->flush();
    
  3. Display Media in Twig:

    <img src="{{ media|media_url({filter: 'admin'}) }}" />
    

Implementation Patterns

Core Workflows

1. Media Upload & Storage

  • Entity Setup: Use the provided Media entity or extend it:
    use Alpixel\Bundle\MediaBundle\Entity\Media;
    class MyMedia extends Media { /* Custom fields */ }
    
  • Form Integration: Use the MediaType form field for drag-and-drop (Dropzone.js) or standard uploads:
    {{ form_start(form) }}
        {{ form_row(form.media) }}
    {{ form_end(form) }}
    
  • Validation: Configure allowed MIME types in config.yml and validate in the controller:
    $media->validate(); // Throws \Exception if invalid
    

2. Image Processing with LiipImagine

  • Configure Filters: Extend config.yml for LiipImagine:
    liip_imagine:
        filter_sets:
            thumbnail:
                quality: 75
                filters:
                    thumbnail: { size: [200, 200], mode: outbound }
    
  • Generate Processed URLs:
    <img src="{{ media|media_url({filter: 'thumbnail'}) }}" />
    
    Or manually in the controller:
    $url = $this->get('alpixel_media.media_url_generator')->generateUrl(
        $media,
        ['filter' => 'thumbnail']
    );
    

3. Media Retrieval & Display

  • Twig Extensions: Use the media_url filter for dynamic URLs:
    {# SEO-friendly public URL #}
    {{ media|media_url({public: true}) }}
    
    {# Absolute URL #}
    {{ media|media_url({absolute: true}) }}
    
    {# Download link #}
    <a href="{{ media|media_url({action: 'download'}) }}">Download</a>
    
  • Controller-Based URLs: Replicate logic from MediaController@showMediaAction:
    $router = $this->get('router');
    $url = $router->generate('alpixel_media_show', [
        'id' => $media->getId(),
        'action' => 'show',
        'filter' => 'thumbnail',
    ]);
    

4. Batch Operations

  • Cleanup Command: Run to remove orphaned files:
    php app/console alpixel:media:cleanup
    
  • Custom Commands: Extend the MediaCommand base class for custom logic.

5. Integration with Entities

  • One-to-Many Relations: Link media to entities:
    /**
     * @ORM\OneToMany(targetEntity="Alpixel\Bundle\MediaBundle\Entity\Media", mappedBy="owner")
     */
    private $media;
    
  • Lifecycle Callbacks: Use events to auto-process media (e.g., generate thumbnails on upload):
    $media->addListener(new \Alpixel\Bundle\MediaBundle\EventListener\MediaListener());
    

Integration Tips

1. Custom Media Types

  • Extend the Media entity to add fields (e.g., altText, caption):
    class ProductImage extends Media {
        /**
         * @ORM\Column(type="string", length=255)
         */
        private $altText;
    }
    
  • Update the form type to include custom fields:
    $builder->add('altText', 'text');
    

2. Dropzone.js Integration

  • Use the provided Dropzone template:
    {% include 'AlpixelMediaBundle:Form:dropzone.html.twig' %}
    
  • Configure Dropzone options in Twig:
    {% set dropzoneOptions = {
        url: path('alpixel_media_upload'),
        maxFilesize: 5,
        acceptedFiles: 'image/*,application/pdf'
    } %}
    

3. Security Considerations

  • File Validation: Always validate MIME types and file sizes server-side:
    $media->setFile($file);
    $media->validate(); // Throws on failure
    
  • Access Control: Restrict media URLs in security.yml:
    access_control:
        - { path: ^/upload/, roles: ROLE_USER }
    

4. Performance Optimization

  • Caching: Leverage LiipImagine’s cache for filtered images:
    liip_imagine:
        filter_sets:
            cache:
                cache: my_cache
    
  • Lazy Loading: Load media URLs dynamically in Twig to reduce server load.

5. Testing

  • Unit Tests: Mock the MediaUrlGenerator and MediaManager services:
    $generator = $this->getMockBuilder('Alpixel\Bundle\MediaBundle\Generator\MediaUrlGenerator')
        ->disableOriginalConstructor()
        ->getMock();
    
  • Functional Tests: Test uploads using HttpFoundation:
    $file = new \Symfony\Component\HttpFoundation\File\UploadedFile(
        __DIR__.'/fixtures/test.jpg',
        'test.jpg'
    );
    $crawler = $this->client->request('POST', '/upload', ['media' => $file]);
    

Gotchas and Tips

Pitfalls

1. Deprecated Features

  • Avoid using <randomMedia> Twig function (deprecated in v2.2.0). Use media_url instead.

2. LiipImagine Dependency

  • Ensure liip/imagine-bundle is installed and configured. Missing filters will break image processing:
    composer require liip/imagine-bundle
    
  • Error: FilterSetNotFoundException if filter_sets are misconfigured in config.yml.

3. File Permissions

  • Issue: Uploads fail with Permission denied if upload_folder lacks write permissions. Fix:
    chmod -R 775 %kernel.root_dir%/../web/upload/
    chown -R www-data:www-data %kernel.root_dir%/../web/upload/
    

4. SEO-Friendly URLs

  • Gotcha: Public URLs (e.g., /upload/filename.jpg) may expose sensitive paths. Mitigation: Use public: false in media_url or restrict access via .htaccess.

5. Database Schema Updates

  • Warning: Running doctrine:schema:update without --force may fail if the Media table exists but is outdated. Fix: Use --force or manually drop the table first.

6. Dropzone.js Conflicts

  • Issue: Dropzone.js may conflict with other JS libraries if not initialized properly. Fix: Wrap Dropzone initialization in $(document).ready() or use data-dz-options.

7. Large File Handling

  • Problem: Default PHP settings may limit uploads (e.g., post_max_size, upload_max_filesize
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon