1

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

mR.Rian
  • 615
  • 2
  • 6
  • 28
Bigbenny
  • 243
  • 1
  • 3
  • 10
  • >> each blog has it own database, Why? – Frank B May 07 '18 at 21:37
  • @FrankB if each blog is seen as one tenant, why not? It's not only better but even suggested to split this way – DonCallisto May 08 '18 at 06:26
  • Is other way to do it without set your enviroment variables? and set config with the variable according to your database. But you have to set 50 env variables. Im right? – Oscar May 08 '18 at 10:30
  • Yes, planning more than 50. – Bigbenny May 08 '18 at 16:49
  • Possbile duplication https://stackoverflow.com/questions/53151669/symfony-change-database-dynamically – SlimenTN Nov 21 '18 at 14:21
  • @SlimenTN that question is clearly related to symfony version 3 and this is about version 4. there are drastic changes in 4 and the code in that other post will do nothing but drastically fail on version 4. please check more thoroughly before claiming a possible duplicate – Jacqueline Loriault Dec 12 '18 at 15:45

2 Answers2

4

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)%'
Amy Anuszewski
  • 1,843
  • 17
  • 30
1

Maybe you can try that from Controller:

$sql = "USE dbname";
$stmt = $this->getDoctrine()->getManager()->getConnection()->prepare($sql);
$stmt->execute();
Andrew Vakhniuk
  • 594
  • 4
  • 12