简体   繁体   中英

Symfony 5 Cannot autowire argument $Driver for a dynamic database connection

I am currently facing a problem, I explain myself. For my project I'm trying to make a dynamic connection to a database (I have 2 virtual machines with a different IP but with the same identifiers and tables with MSSQL database engine (SQLSRV)).

I try something like this ->

use Doctrine\DBAL\Driver\SQLSrv\Driver;
 /**
 * @Route("/testconnection", name="test_connect")
 */
public function testConnection(Driver $Driver){

    $connectionParams = array(
        'dbname' => 'job',
        'user' => 'sa',
        'password' => 'Lasernet@2020',
        'host' => '192.168.1.34',
        'driver' => 'pdo_sqlsrv',
    );

    $conn = $Driver->connect($connectionParams);
    dd($conn);
}

Error message

Cannot autowire argument $Driver of "App\Controller\HomeController:testConnection()": it references class "Doctrine\DBAL\Driver\SQLSrv\Driver" but no such services exists.

Error message

But the problem is that Symfony sends me back an error that I find hard to solve/understand. If someone has a solution to my problem/success to make a dynamic connection to databases.

If you need more information tell me.

The error message says it. No such service exists. You must define the Doctrine\DBAL\Driver\SQLSrv\Driver class as a symfony service in your public/services.yaml to autowire it.

Update your public/services.yaml with:

services:
    
    Doctrine\DBAL\Driver\SQLSrv\Driver:
        autowire: true

But why you will autowire this class? The same behaviour you can get with

public function testConnection(){
    $Driver = new Driver();
    $connectionParams = array(
        'dbname' => 'job',
        'user' => 'sa',
        'password' => 'Lasernet@2020',
        'host' => '192.168.1.34',
        'driver' => 'pdo_sqlsrv',
    );

    $conn = $Driver->connect($connectionParams);
    dd($conn);
}

And if you have no really dynamic values in your connection params like $connectionParams['dbname'] = 'sqldb'.$i , better to use the doctrine dbal config and get the connection with $this->getDoctrine()->getConnection('name'); in your controller.

Symfony Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM