I am structuring a Symfony 4 application which is also using API Platform. The problem is that we have a demand that a User will have to connect to its own database. So each time it logs in to a centralized domain (just for access purposes), the application will have to connect him to his own database.
I've done some research, and found out that the closest thing specified in Symfony 4 docs is the Multiple Entity Managers and Connections.
The problem here is that although it shows how to create multiple configurations for different database connections, it just specifies how to create them for a specific Entity Manager, or how to get stuff from another Entity Manager inside a Symfony Controller.
In my case, we don't have any Controllers. Instead, there is an API with a couple of services endpoints which connect to the database to manage resources though HTTP requests. Currently, we are using always the default database connection, which gets the configuration from the .env variable.
I know that will have to store this database configuration information in a session (or anything similar) or verify which database is the right one for the given user at each API request. But I'm not so sure what's the best way to deal with this problem.
Also, I thought of creating a listener to the onKernelRequest event, as described in this thread
Any thoughts or ideas how should I proceed with this?
EDIT
This is the packages/doctrine.yaml file. Everything is configured for default.
parameters:
# Adds a fallback DATABASE_URL if the env var is not set.
# This allows you to run cache:warmup even if your
# environment variables are not available yet.
# You should not need to change this value.
env(DATABASE_URL): ''
doctrine:
dbal:
# configure these for your database server
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
url: '%env(resolve:DATABASE_URL)%'
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Fst\Entity'
alias: App
And for the .env file:
DATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_name
which is overrided in the .env.local file.
Also, services.yaml has default configuration, with autowiring enabled.