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

Sonata Media Extended Bundle Laravel Package

anacona16/sonata-media-extended-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require anacona16/sonata-media-extended-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Anacona16\SonataMediaExtendedBundle\SonataMediaExtendedBundle::class => ['all' => true],
    ];
    
  2. Prerequisites Ensure you have SonataMediaBundle installed (v2.3, 3.0, or 4.0) and configured. This bundle extends it, so core functionality (providers, formats, media managers) must already exist.

  3. First Use Case Extend SonataMediaBundle’s default behavior (e.g., custom media providers, formats, or admin configurations) without modifying the core bundle. Example:

    php bin/console sonata:easy-extends:generate --dest=src SonataMediaBundle
    

    This generates a skeleton for extensions in src/SonataMediaBundle/.


Implementation Patterns

1. Extending Media Providers

Override or add providers (e.g., AWS S3, custom upload handlers) by:

  • Creating a service tagged as sonata.media.provider in src/SonataMediaBundle/Resources/config/services.yml:
    services:
        app.media.provider.custom:
            class: App\SonataMediaBundle\Provider\CustomProvider
            tags:
                - { name: sonata.media.provider, provider: custom }
    
  • Implement Sonata\MediaBundle\Model\MediaProviderInterface.

2. Custom Media Formats

Add formats (e.g., PDF thumbnails) by:

  • Defining a format service in services.yml:
    app.media.format.pdf_thumbnail:
        class: App\SonataMediaBundle\Format\PdfThumbnailFormat
        arguments: ["@sonata.media.pool"]
        tags:
            - { name: sonata.media.format, format: pdf_thumbnail }
    
  • Implement Sonata\MediaBundle\Provider\FormatInterface.

3. Admin Customization

Extend the SonataMediaBundle admin class (e.g., MediaAdmin) in src/SonataMediaBundle/Admin/MediaAdmin.php:

namespace App\SonataMediaBundle\Admin;

use Sonata\MediaBundle\Admin\MediaAdmin as BaseMediaAdmin;

class MediaAdmin extends BaseMediaAdmin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper->add('custom_field', 'text');
    }
}

Register it in services.yml:

sonata.media.admin.media:
    class: App\SonataMediaBundle\Admin\MediaAdmin
    arguments: [~, App\SonataMediaBundle\Entity\Media, App\SonataMediaBundle:MediaAdmin]
    tags:
        - { name: sonata.admin, manager_type: orm, group: media, label: Media }

4. Event Listeners/Subscribers

Hook into SonataMediaBundle events (e.g., sonata.media.pre_persist) in src/SonataMediaBundle/EventListener/:

namespace App\SonataMediaBundle\EventListener;

use Sonata\MediaBundle\Event\MediaEvent;

class CustomMediaListener
{
    public function onPrePersist(MediaEvent $event)
    {
        $media = $event->getSubject();
        $media->setCustomMetadata('processed', true);
    }
}

Register the listener in services.yml:

app.media.listener.custom:
    class: App\SonataMediaBundle\EventListener\CustomMediaListener
    tags:
        - { name: kernel.event_listener, event: sonata.media.pre_persist, method: onPrePersist }

5. Twig Extensions

Add custom Twig filters/functions for media rendering in src/SonataMediaBundle/Twig/Extension.php:

namespace App\SonataMediaBundle\Twig;

class MediaExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('custom_media_url', [$this, 'getCustomMediaUrl']),
        ];
    }

    public function getCustomMediaUrl($media, $format = 'reference')
    {
        return $media->getReference($format);
    }
}

Register it in services.yml:

app.media.twig.extension:
    class: App\SonataMediaBundle\Twig\MediaExtension
    tags:
        - { name: twig.extension }

Gotchas and Tips

Pitfalls

  1. Dependency Conflicts

    • Ensure your sonata-project/media-bundle version matches the bundle’s requirements (^2.3|^3.0|^4.0). Mixing versions may break functionality.
    • Debug Tip: Run composer why-not sonata-project/media-bundle:4.0 to check compatibility.
  2. Namespace Collisions

    • If you generate extensions with sonata:easy-extends:generate, ensure the generated src/SonataMediaBundle namespace doesn’t conflict with existing bundles (e.g., App\SonataMediaBundle vs. App\MediaBundle).
    • Fix: Rename the generated bundle folder if needed.
  3. Caching Issues

    • After extending providers/formats, clear the cache:
      php bin/console cache:clear
      
    • Debug Tip: Use bin/console debug:container sonata.media.provider to verify your custom provider is registered.
  4. Missing Event Dispatcher

    • If using event listeners, ensure the EventDispatcherInterface is injected. SonataMediaBundle v4+ uses Symfony’s event system by default.
    • Fix: Autowire the dispatcher or add it manually:
      arguments: ["@event_dispatcher"]
      
  5. Admin Overrides Not Loading

    • If custom MediaAdmin isn’t applied, check:
      • The service is properly tagged (sonata.admin).
      • The manager_type matches your Doctrine setup (orm or mongodb).
      • Debug Tip: Run bin/console debug:container sonata.media.admin.media to inspect the service.

Tips

  1. Leverage sonata:easy-extends:dump After generating extensions, dump the current state to see what’s been overridden:

    php bin/console sonata:easy-extends:dump
    
  2. Debugging Media Providers Add logging to your custom provider to verify it’s being called:

    use Psr\Log\LoggerInterface;
    
    class CustomProvider implements MediaProviderInterface
    {
        public function __construct(private LoggerInterface $logger)
        {
        }
    
        public function write($directory, $name, $data, $format = null)
        {
            $this->logger->info('Custom provider writing file', ['name' => $name]);
            // ...
        }
    }
    
  3. Dynamic Format Configuration Use YAML to define formats dynamically in config/packages/sonata_media.yaml:

    sonata_media:
        formats:
            custom_thumb:
                provider: sonata.media.provider.image
                extension: jpg
                max_width: 200
                max_height: 200
    
  4. Testing Extensions Test custom providers/formats in isolation using PHPUnit:

    use Sonata\MediaBundle\Tests\Functional\MediaTestCase;
    
    class CustomProviderTest extends MediaTestCase
    {
        public function testProvider()
        {
            $provider = $this->get('app.media.provider.custom');
            $this->assertInstanceOf(MediaProviderInterface::class, $provider);
        }
    }
    
  5. Performance Optimization

    • For large media libraries, lazy-load providers/formats by implementing Sonata\MediaBundle\Provider\LazyProviderInterface.
    • Example:
      class LazyImageProvider implements MediaProviderInterface, LazyProviderInterface
      {
          public function isLazy()
          {
              return true;
          }
      
          public function getLazyContext()
          {
              return ['provider' => 'image'];
          }
      }
      
  6. Upgrading SonataMediaBundle

    • If upgrading the core bundle, test your extensions thoroughly. Use sonata:easy-extends:generate again to regenerate the skeleton if needed.
    • Tip: Backup your src/SonataMediaBundle before upgrading.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware