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?