Symfony 3.4 – switch to dynamic database from command

Recently I’ve been busy upgrading an older project from Symfony 2.7 to 3.4. The project uses a custom multi tenant setup and relies on a EventListener to switch between databases based on subdomain. This works since I can define the priority of that EventListener in my services.yml file so it’s loaded before any other services. By doing that all my other code uses that database set by the listener.

    current_site_listener:
        class: AppBundleEventListenerCurrentSiteListener
        arguments: ["@doctrine.dbal.default_connection", "%base_host%"]
        tags:
          - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 10 }

So far so good, but unfortunately that logic does not work for any of my tenant specific commands. These commands use an argument option to define which database should be used. Since I can’t define a priority for these commands the other services are already loaded and I am not able to override the database connection from within the command. The code below is what I’m using in both the command and EventListener and works fine in the latter (and also worked fine in Symfony 2.7 within the command).

        $connectionParams = array(
            'dbname' => $client['database_name'],
            'user' => $client['database_login'],
            'password' => $client['database_password'],
            'host' => $client['database_host'],
            'driver' => 'pdo_mysql',
            'charset' =>  'UTF8'
        );

        /** @var Connection $connection */
        $connection = $this->container->get('doctrine.dbal.default_connection');

        if ($connection->isConnected()) {
            $connection->close();
        }
        $connection->__construct(
            $connectionParams, $connection->getDriver(), $connection->getConfiguration(),
            $connection->getEventManager()
        );

The code above was working fine in Symfony 2.7 but my guess is that between that version and Symfony 3.4 something has changed in the way services work and I am not able to override them anymore with my current database connection. I haven’t come across any changes regarding this issue in the migration docs and am therefore clueless on how to solve this. I’m hoping someone on here has any ideas or suggestions on how to fix this.

Thanks in advance and kind regards,

Kevin

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *