[英]Symfony inject service container into doctrine connection wrapper
I try to inject the symfony service container into a dcotrine dynamic connection wrapper_class 我尝试将symfony服务容器注入到dcotrine动态连接wrapper_class中
use Doctrine\DBAL\Connection;
class DynamicConnection extends Connection
{
public $container;
/**
* @required
* @param $container
*/
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}
}
I also tried to inject it with the service.yaml 我也尝试用service.yaml注入它
App\Service\Database\DynamicConnection:
calls:
- [setContainer, ['@service_container']]
But this is also not working. 但这也不起作用。 How can i inject the service container here?
我如何在这里注入服务容器? My goal here is to get a variable of the service container:
我的目标是获取服务容器的变量:
$this->container->get('my.string.variable')
You can do this by adding a CompilerPass
. 您可以通过添加
CompilerPass
。 For simple CompilerPass
, you can add it directly in your application Kernel
class by implementing CompilerPassInterface
: 对于简单的
CompilerPass
,您可以通过实现CompilerPassInterface
将其直接添加到应用程序的Kernel
类中:
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
...
public function process(ContainerBuilder $container)
{
$container
->getDefinition('doctrine.dbal.default_connection')
->addMethodCall('setContainer', [
new Reference('service_container')
]);
}
}
Note however that as mentioned by other users, this is not a very good practice. 但是请注意,正如其他用户所提到的,这不是一个很好的做法。 You should inject what you need precisely instead of Container service.
您应该准确注入所需的内容,而不是容器服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.