SonataMediaBundle Documentation

repository·4.x·Indexed 19 days ago

https://github.com/sonata-project/sonatamediabundle

A Symfony bundle for comprehensive media management within Symfony and SonataAdmin applications. It features a provider-based architecture to handle various media types (images, files, YouTube, Vimeo, Dailymotion) and abstracts the storage layer via filesystem services (Local, FTP, S3, Azure) and CDN services (Local, CloudFront, Panther). The bundle supports media contexts, custom formats, thumbnail generation, and provides CLI tools for metadata updates and mass imports.

Tokens
22.7K
Snippets
68
Records
88
Agent score
66%

What's inside SonataMediaBundle

  1. Overview of SonataMediaBundle

    4.x
    SonataMediaBundle is a Symfony bundle designed to manage media assets within a Symfony application. It provides tools for handling various types of media files, typically integrated within the SonataAdmin ecosystem to facilitate media uploads, management, and storage.
  2. What is a Media Provider and how does it work?

    4.x

    A provider class manages a specific type of media (e.g., a YoutubeProvider for videos or an ImageProvider for images). It is responsible for handling media-specific tasks such as:

    • Generating thumbnails
    • Managing the media path
    • Providing forms for creating and editing the media
    • Storing and retrieving media metadata

    Providers are linked to a Filesystem (using the Gaufrette library) and a CDN for generating public URLs. By default, these use the local filesystem and the current server.

    When implementing a provider, you interact with the Media entity, which contains common fields (size, length, width, height) and provider-specific fields:

    • provider_name: The service name of the provider.
    • provider_status: The status of the media.
    • provider_reference: An internal reference (e.g., a video ID).
    • provider_metadata: A field used to store extra information as a serialized array.
  3. Understand and configure Media Contexts

    4.x

    A context in SonataMediaBundle allows you to group specific media providers and formats for different use cases (e.g., 'user pictures' vs 'news pictures'). This isolation ensures that a 'small' format in one context can have different dimensions or providers than a 'small' format in another.

    Key configuration options within a context:

    • providers: A list of media providers available in this context.
    • formats: A set of defined sizes/qualities. Each format can specify:
      • width: The target width.
      • quality: The image quality.
      • resizer: A custom resizer service (overrides the provider's default).
      • constraint: If set to false, the uploaded image is allowed to be smaller than the defined format size.
    # config/packages/sonata_media.yaml
    
    sonata_media:
        contexts:
            default:  # the default context is mandatory
                providers:
                    - sonata.media.provider.image
                    - sonata.media.provider.file
                formats:
                    small: { width: 100, quality: 70 }
                    big: { width: 500, quality: 70, resizer: sonata.media.resizer.square }
    
            news:
                providers:
                    - sonata.media.provider.image
                formats:
                    small: { width: 150, quality: 95 }
                    big: { width: 500, quality: 90, constraint: false }
  4. How SonataMediaBundle works

    4.x

    The SonataMediaBundle is a media library that uses a provider-based architecture to manage different media types such as files, videos, or images.

    Each media type is managed by a dedicated provider service. A provider is responsible for:

    • Retrieving media metadata
    • Generating media thumbnails
    • Tweaking the edit form
    • Rendering the media

    Media can be organized into contexts (e.g., news, user). A context allows you to group related media together and defines specific requirements for that group via a set of formats and providers.

    The bundle abstracts both the filesystem layer (where files are stored) and the cdn layer (how files are served).

  5. Understand Media Download Security Strategies

    4.x

    SonataMediaBundle uses a download strategy interface to authorize media retrieval. Since original files may be private, a strategy determines if a user is allowed to download a file for a specific context.

    Built-in Security Strategies

    • sonata.media.security.superadmin_strategy: (DEFAULT) Requires ROLE_SUPER_ADMIN or ROLE_ADMIN.
    • sonata.media.security.public_strategy: No restrictions; files are public.
    • sonata.media.security.forbidden_strategy: Retrieval of the original file is impossible.
    • sonata.media.security.connected_strategy: Requires the user to be authenticated (IS_AUTHENTICATED_FULLY or IS_AUTHENTICATED_REMEMBERED).
  6. Configure Media Download Modes

    4.x

    Download modes determine how the file is sent from the server to the client. The choice depends on your HTTP server configuration:

    • http: (DEFAULT) Uses PHP to send the file. Use this if you are unsure about server compatibility.
    • X-Sendfile: Uses the X-Sendfile header (requires Apache + mod_xsendfile).
    • X-Accel-Redirect: Uses the X-Accel-Redirect header (requires Nginx).

    Important: If you use X-Sendfile or X-Accel-Redirect, you must explicitly trust the header in your application controller by calling BinaryFileResponse::trustXSendfileTypeHeader();.

  7. Configure a Media Context with a Security Strategy

    4.x

    You can define the download strategy and mode within a media context in your sonata_media.yaml configuration file. To generate download links in Twig, use the sonata_media_download route with the media's URL-safe ID.

    # config/packages/sonata_media.yaml
    
    sonata_media:
        db_driver: doctrine_orm
        contexts:
            default:
                download:
                    strategy: sonata.media.security.superadmin_strategy
                    mode: http
                providers:
                    - sonata.media.provider.file
    {# In a Twig template #}
    <a href="{{ path('sonata_media_download', {'id': media|sonata_urlsafeid }) }}">Download file</a>
  8. Configure custom Buzz HTTP client for media providers

    4.x

    SonataMediaBundle 4.0 dropped support for kriswallsmith/buzz. If you use media provider services that rely on Buzz, you must create a custom service based on the Buzz client and register it in your configuration using Psr\Http\Client\ClientInterface and Psr\Http\Message\RequestFactoryInterface.

    sonata_media:
        http:
            client: 'your_custom.buzz_client' # Psr\Http\Client\ClientInterface
            message_factory: 'your_custom.message_facory' # Psr\Http\Message\RequestFactoryInterface
  9. Use MediaBundle view helpers for thumbnails and media

    4.x

    The MediaBundle provides two helper methods to display media in Twig templates:

    • thumbnail: Displays a thumbnail image based on the requested format. The path is generated using the CDN service injected into the provider (defaults to the sonata.media.cdn.server service).
    • media: Displays the actual media (e.g., a video player). This method calls getHelperProperties on the provider to normalize available options for the template.

    To use these, you typically call them within your Twig templates, passing the media entity and desired options.