문제

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);
  }
도움이 되었습니까?

해결책

is there any method to check if the connection is available or not?

If you mean class method, then no, because it wouldn’t be necessary. You can simply catch the exception, which will tell you immediately that the connection was not successful:

try {
  // Code using a database connection
} catch (ConnectionNotDefinedException $e) {
  // No database for you
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 drupal.stackexchange
scroll top