Switch storage backends at runtime using a lazy adapter
3.xWhile the standard way to switch storage backends is to use environment-specific configuration files (e.g., config/packages/dev/flysystem.yaml), you can use a lazy adapter to choose a storage backend dynamically at runtime.
A lazy adapter acts as a proxy that delays the instantiation of the actual storage until it is needed. This is particularly useful when you need to switch backends based on a single environment variable without creating multiple service definitions for different environments.
To implement this, define your actual storage backends as separate services, then define a main storage service using the lazy key and point its source to the desired backend via an environment variable.
# config/packages/flysystem.yaml
flysystem:
storages:
uploads.storage.aws:
aws:
client: 'Aws\S3\S3Client'
bucket: 'my-bucket'
prefix: '%env(S3_STORAGE_PREFIX)%'
uploads.storage.local:
local:
directory: '%kernel.project_dir%/var/storage/uploads'
uploads.storage.memory:
memory: ~
uploads.storage:
lazy:
source: '%env(APP_UPLOADS_SOURCE)%'