Bigbenny
Bigbenny

Reputation: 253

Symfony 4 changing databases on the fly

I'm working on a blog platform, each blog has it own database.

I need to switch database connection on the fly.

I understand the documentation

http://symfony.com/doc/current/doctrine/multiple_entity_managers.html

But i would like to avoid to add everyting in the config file as there are more

than 50 databases.

I ve been trying to adapt this code to symfony 4 but i couldn t make it work https://stackoverflow.com/a/9291896/9726140

Thank you

Upvotes: 1

Views: 2169

Answers (2)

Amy Anuszewski
Amy Anuszewski

Reputation: 1853

I figured out something for my own situation in which each customer had their own subdomain. I can take advantage of the virtual hosts section of the apache config to add an extra environment variable and use that to set the database name.

In apache: # ...

    SetEnv SUBDOMAIN_NAME "db_name"
</VirtualHost>

IN my .env for development (This would go above in apache config for prod) Basically, just strip the database name from the URL

DATABASE_URL=mysql://root:root@mysql:3306/

Finally, in my doctrine.yaml under parameters, I set a default value. This way, we don't blow errors for unconfigured customers and can show a nice clean 'setup necessary' message for tech support:

env(SUBDOMAIN_NAME): 'default_customer'

and in doctrine.yaml, replace the value for url with

url: '%env(resolve:DATABASE_URL)%%env(resolve:SUBDOMAIN_NAME)%'

Upvotes: 4

Andrew Vakhniuk
Andrew Vakhniuk

Reputation: 594

Maybe you can try that from Controller:

$sql = "USE dbname";
$stmt = $this->getDoctrine()->getManager()->getConnection()->prepare($sql);
$stmt->execute();

Upvotes: 1

Related Questions