Setting up dependency configuration at runtime in Symfony 2?

In my reusable package, I can specify the connection name (Doctrine DBAL connection):

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

      

In the extension, I flatten it:

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

      

And entering it where necessary (4-5 services included). Everything works fine.

Unfortunately, it turns out that the connection must (might) be changed at runtime , i.e. after user authentication (i.e. with HTTP Basic Authentication). When username foo

, use foo_database

when bar

, then bar_database

.

My solution (workaround):

Now I change it using the event system : when something in the package uses the object Connection

, I highlight the event, i.e. MyBundle::BAR

event. The listener can change the connection with setConnection(Connection $connection)

. Then in my package, I use the updated connection calling getConnection()

.

This solution, however, forces me to listen to every event that needs to be changed. What if I forgot to listen to the event MyBundle::FOO

? My application will not work as expected and errors will be difficult to understand and track.

Is there a good way to solve this problem?

+3


source to share





All Articles