I have 2 databases, the first one with Drupal and the second one with external data. In a controller I want to read data from that second database and display it.
As the external database can be available or not, is there any method to check if the connection is available or not?
My code is working, but if the DB is not available (or unset) I get the following error:
Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: schedules in Drupal\Core\Database\Database::openConnection() (line 364 of core/lib/Drupal/Core/Database/Database.php).
Code:
abstract class AbstractSchedulesRepository {
/**
* Schedules repository target.
*/
public const SCHEDULES_REPOSITORY_TARGET_DATABASE = 'default';
/**
* Schedules repository key.
*/
public const SCHEDULES_REPOSITORY_KEY_DATABASE = 'schedules';
/**
* Drupal\schedules\Repository\SchedulesCache definition.
*
* @var \Drupal\schedules\Cache\SchedulesCache
*/
protected $schedulesCache;
/**
* Drupal\Core\Language\LanguageManager definition.
*
* @var \Drupal\Core\Language\LanguageManager
*/
protected $languageManager;
/**
* Drupal\Core\Database\Connection definition.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Constructor.
*
* @param \Drupal\schedules\Cache\SchedulesCache $schedulesCache
* Schedules cache.
* @param \Drupal\Core\Language\LanguageManager $languageManager
* Language manager.
*/
public function __construct(SchedulesCache $schedulesCache, LanguageManager $languageManager) {
$this->schedulesCache = $schedulesCache;
$this->languageManager = $languageManager;
$this->connection = Database::getConnection(self::SCHEDULES_REPOSITORY_TARGET_DATABASE, self::SCHEDULES_REPOSITORY_KEY_DATABASE);
}
ConnectionNotDefinedException
?connectionAvailable
or similar method would have to actually make a connection, which costs time. As you’re already planning to make a connection, that’s wasted time. Better that you just make the connection and observe the result than cost yourself two connections by checking up front