簡體   English   中英

Symfony將服務容器注入到理論連接包裝器中

[英]Symfony inject service container into doctrine connection wrapper

我嘗試將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;
    }
}

我也嘗試用service.yaml注入它

    App\Service\Database\DynamicConnection:
    calls:
        - [setContainer, ['@service_container']]

但這也不起作用。 我如何在這里注入服務容器? 我的目標是獲取服務容器的變量:

$this->container->get('my.string.variable')

您可以通過添加CompilerPass 對於簡單的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')
           ]);
    }

}

但是請注意,正如其他用戶所提到的,這不是一個很好的做法。 您應該准確注入所需的內容,而不是容器服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM