SonataMediaBundle Documentation
repository·4.x·Indexed 19 days ago
https://github.com/sonata-project/sonatamediabundleA 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.
What's inside SonataMediaBundle
- 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.
What is a Media Provider and how does it work?
4.xA provider class manages a specific type of media (e.g., a
YoutubeProviderfor videos or anImageProviderfor 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 theGaufrettelibrary) and aCDNfor generating public URLs. By default, these use the local filesystem and the current server.When implementing a provider, you interact with the
Mediaentity, 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.
Understand and configure Media Contexts
4.xA
contextin 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 tofalse, 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 }How SonataMediaBundle works
4.xThe
SonataMediaBundleis 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).
Understand Media Download Security Strategies
4.xSonataMediaBundle 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) RequiresROLE_SUPER_ADMINorROLE_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_FULLYorIS_AUTHENTICATED_REMEMBERED).
Best practices for S3 configuration
4.xWhen configuring the S3 filesystem, avoid usingversion: "latest"in production environments. Pulling in a new minor version of the SDK that includes an API update could potentially break your production application. It is recommended to specify a fixed version.Configure Media Download Modes
4.xDownload 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 theX-Sendfileheader (requires Apache +mod_xsendfile).X-Accel-Redirect: Uses theX-Accel-Redirectheader (requires Nginx).
Important: If you use
X-SendfileorX-Accel-Redirect, you must explicitly trust the header in your application controller by callingBinaryFileResponse::trustXSendfileTypeHeader();.Install the Azure Blob Storage package
4.xTo use Azure Blob Storage with SonataMediaBundle, you must install the Microsoft Azure Storage Blob PHP library via Composer.
composer require microsoft/azure-storage-blobCreate Media Uploads Directory
4.xEnsure the directory used for media uploads exists and is writable by the HTTP user.
mkdir -p public/uploads/mediaConfigure a Media Context with a Security Strategy
4.xYou can define the download strategy and mode within a media context in your
sonata_media.yamlconfiguration file. To generate download links in Twig, use thesonata_media_downloadroute 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>Configure custom Buzz HTTP client for media providers
4.xSonataMediaBundle 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 usingPsr\Http\Client\ClientInterfaceandPsr\Http\Message\RequestFactoryInterface.sonata_media: http: client: 'your_custom.buzz_client' # Psr\Http\Client\ClientInterface message_factory: 'your_custom.message_facory' # Psr\Http\Message\RequestFactoryInterfaceUse MediaBundle view helpers for thumbnails and media
4.xThe
MediaBundleprovides 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 thesonata.media.cdn.serverservice).media: Displays the actual media (e.g., a video player). This method callsgetHelperPropertieson 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.