/** * Test multiple db resources by looping over 2 clients and connecting * to their and their own specified dbResources which will share the same * connection name across both clients */ public function testLoopThroughDifferentClients() { $dbFactory = \Yii::$app->get('dbFactory'); $clients = Client::find()->orderBy('id')->all(); foreach ($clients as $client) { $this->assertInstanceOf(Client::className(), $client); $this->setService('client', $client); // get the dbClient connection (should be based on the 'client' component setup above //$db = $dbFactory->getConnection('dbClient', true); $db = $dbFactory->getClientConnection(true); // command equivalent to the above // $db should now be the connection to the current client (not connected) $this->assertInstanceOf(Connection::className(), $db); $this->assertEquals($client->dbDsn, $db->dsn); $this->assertEquals(2, $dbFactory->getResourceCount()); // we should be able to get a connection $this->assertTrue($dbFactory->connectResource('dbClient')); $this->assertTrue($dbFactory->isResourceConnected('dbClient')); $this->assertInstanceOf('\\PDO', $db->pdo); $customer = new Customer(); if ($client->clientCode == 'CLIENT1') { $this->assertTrue(!$customer->hasAttribute('extraField')); } else { // the customer table for CLIENT2 has an extra extraField attribute $this->assertTrue($customer->hasAttribute('extraField')); } // find details of the current clients dbRemote connection $dbResource = ClientDbResource::find()->where(['resourceName' => 'dbRemote'])->one(); // now attempt to get a connection to the specific clients dbRemote resource as defined // in the clients.dbResources table //$dbRemote = $dbFactory->getConnection('dbClient', true, false, true); $dbRemote = $dbFactory->getClientResourceConnection('dbRemote', true); // identical to the getConnection() call above // $dbRemote should now be the connection to the current clients dbRemote resource (not connected) $this->assertInstanceOf(Connection::className(), $dbRemote); $this->assertEquals($dbResource->dbDsn, $dbRemote->dsn); $this->assertEquals(3, $dbFactory->getResourceCount()); // we should be able to get a connection $this->assertTrue($dbFactory->connectResource('dbRemote')); $this->assertTrue($dbFactory->isResourceConnected('dbRemote')); $this->assertInstanceOf('\\PDO', $dbRemote->pdo); if ($client->clientCode == 'CLIENT1') { $this->assertRegExp('/dbTestRemote1/', $dbRemote->dsn); } else { $this->assertRegExp('/dbTestRemote2/', $dbRemote->dsn); } $robot = Robot::findOne(1); if ($client->clientCode == 'CLIENT1') { $this->assertTrue(!$robot->hasAttribute('extraField')); } else { // the robot table for CLIENT2s dbRemote connection has an extra extraField attribute $this->assertTrue($robot->hasAttribute('extraField')); } $this->assertTrue($dbFactory->removeAllResources()); $this->assertEquals(1, $dbFactory->getResourceCount()); } $this->assertTrue($dbFactory->removeAllResources(true)); $this->assertEquals(0, $dbFactory->getResourceCount()); }