Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

php - 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 DoctrineDBALDriverSQLSrvDriver;
 /**
 * @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 "AppControllerHomeController:testConnection()": it references class "DoctrineDBALDriverSQLSrvDriver" 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.

question from:https://stackoverflow.com/questions/65844957/symfony-5-cannot-autowire-argument-driver-for-a-dynamic-database-connection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Update your public/services.yaml with:

services:
    
    DoctrineDBALDriverSQLSrvDriver:
        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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...