[英]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)).
对于我的项目,我正在尝试与数据库建立动态连接(我有 2 个虚拟机,它们具有不同的 IP,但具有相同的标识符和具有 MSSQL 数据库引擎(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.无法自动装配“App\Controller\HomeController:testConnection()”的参数 $Driver:它引用 class “Doctrine\DBAL\Driver\SQLSrv\Driver”,但不存在此类服务。
But the problem is that Symfony sends me back an error that I find hard to solve/understand.但问题是 Symfony 向我发送了一个我发现难以解决/理解的错误。 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.您必须在
public/services.yaml
中将Doctrine\DBAL\Driver\SQLSrv\Driver
class 定义为 symfony 服务以自动装配它。
Update your public/services.yaml
with:更新您的
public/services.yaml
:
services:
Doctrine\DBAL\Driver\SQLSrv\Driver:
autowire: true
But why you will autowire this class?但是为什么你要自动装配这个 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');
如果您的连接参数中没有真正的动态值,例如
$connectionParams['dbname'] = 'sqldb'.$i
,最好使用 doctrine dbal 配置并使用$this->getDoctrine()->getConnection('name');
in your controller.在您的 controller 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.