How to set up and inject multiple PDO database connections in slim 4?

后端 未结 2 1132
野性不改
野性不改 2021-01-13 15:23

I could make an instance of PDO and inject it successfully. I defined the PDO::class directly and injected it in the constructor with __const

相关标签:
2条回答
  • 2021-01-13 15:41

    You have multiple options:

    1. Extending PDO
    2. Autowired objects

    1. Extending PDO

    use PDO;
    
    class PDO2 extends PDO
    {
        // must be empty
    }
    

    The container definition:

    use PDO2;
    
    // ...
    
    return [
        PDO::class => function (ContainerInterface $container) {
            return new PDO(...);
        },
    
        PDO2::class => function (ContainerInterface $container) {
            return new PDO2(...);
        },
    ];
    

    Usage

    use PDO;
    use PDO2;
    
    class MyRepository
    {
        private $pdo;
    
        private $pdo2;
        
        public function __construct(PDO $pdo, PDO2 $pdo2)
        {
            $this->pdo = $pdo;
            $this->pdo2 = $pdo2;
        }
    }
    

    2. Autowired objects

    See Matthieu Napoli's answer: https://stackoverflow.com/a/57758106/1461181

    0 讨论(0)
  • 2021-01-13 15:55

    If you have multiple instances of a class in your app (here you have multiple instances of the PDO class), then you must configure which one to inject every time.

    That means that PDO cannot be autowired, because PHP-DI cannot decide which instance you want depending on the service/controller/etc.

    You need to use configuration (see http://php-di.org/doc/php-definitions.html#autowired-objects) to define which instance (db1 or db2 in your example) to inject for each service.

    return [
        MyService::class => DI\autowire()
            ->constructorParameter('pdo', DI\get('db1'))
            ->constructorParameter('pdo2', DI\get('db2')),
    
        'db1' => function (ContainerInterface $c) {
            return new PDO();
        },
        'db2' => function (ContainerInterface $c) {
            return new PDO();
        },
    ];
    
    0 讨论(0)
提交回复
热议问题