3

In my reusable bundle, I can specify a connection name (Doctrine DBAL connection):

# config.yml
my_bundle:
    connection: ~ # or "default", or "my_connection"

In the extension, I'm aliasing it:

// MyBundleExtension.php
$container->setAlias(
    'my_bundle.connection',
    'doctrine.dbal.'.$config['connection'].'_connection'
);

And injecting it where needed (4-5 services in the bundle). All works fine.

Unfortunatly, it turns out that connection should (may) be changed at runtime, i.e. after the user as been authenticated (i.e with HTTP basic authentication). When username is foo, then use foo_database, when bar then bar_database.

My solution (workaround):

Right now I'm changing it using the event system: when something in the bundle uses a Connection object, I emit an event, i.e MyBundle::BAR event. A listener can change the connection using setConnection(Connection $connection). Then in my bundle, I use the updated connection calling getConnection().

This solution however forces me to listen to every event that need to change the connection. What if i forgot to listen to MyBundle::FOO event? My application would not work as expected and bugs would be difficult to understand and track.

Is there a good way to solve this problem?

gremo
  • 47,186
  • 75
  • 257
  • 421
  • I know Sylius does some magic with container parameters, so that interfaces can be defined in Doctrine mappings and a base model class can be used with Doctrine ORM or Doctrine MongoDB ODM, without having to specify `Entity` and `Document` classes respectively. I think this can be done by overriding `MyBundle::boot()` and manipulating the parameters there. – Adam Elsodaney Oct 07 '14 at 19:31
  • @AdamElsodaney hey, thanks. Can you point me to the right class or file? – gremo Oct 07 '14 at 19:49

0 Answers0