简体   繁体   中英

Symfony inject service container into doctrine connection wrapper

I try to inject the symfony service container into a dcotrine dynamic connection 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

    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 . For simple CompilerPass , you can add it directly in your application Kernel class by implementing CompilerPassInterface :

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.

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