You are here

class ClientFactory in MongoDB 8.2

Helper class to construct a MongoDB client with Drupal specific config.

Hierarchy

Expanded class hierarchy of ClientFactory

3 files declare their use of ClientFactory
ClientFactoryTest.php in modules/mongodb/tests/src/Kernel/ClientFactoryTest.php
DatabaseFactoryTest.php in modules/mongodb/tests/src/Kernel/DatabaseFactoryTest.php
MongoDbTestBase.php in modules/mongodb/tests/src/Kernel/MongoDbTestBase.php
1 string reference to 'ClientFactory'
mongodb.services.yml in modules/mongodb/mongodb.services.yml
modules/mongodb/mongodb.services.yml
1 service uses ClientFactory
mongodb.client_factory in modules/mongodb/mongodb.services.yml
Drupal\mongodb\ClientFactory

File

modules/mongodb/src/ClientFactory.php, line 13

Namespace

Drupal\mongodb
View source
class ClientFactory {

  /**
   * The 'mongodb' client settings.
   *
   * @var string[][]
   */
  protected $settings;

  /**
   * A hash of connections per alias.
   *
   * @var \MongoDB\Client[]
   */
  protected $clients;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Site\Settings $settings
   *   The system settings.
   */
  public function __construct(Settings $settings) {
    $this->settings = $settings
      ->get(MongoDb::MODULE)['clients'];
  }

  /**
   * Return a Client instance for a given alias.
   *
   * @param string $alias
   *   The alias defined in settings for a Client.
   *
   * @return \MongoDB\Client
   *   A Client instance for the chosen server.
   */
  public function get($alias) {
    if (!isset($this->clients[$alias]) || !$this->clients[$alias] instanceof Client) {
      $info = $this->settings[$alias] ?? [];
      $info += [
        'uri' => 'mongodb://localhost:27017',
        'uriOptions' => [],
        'driverOptions' => [],
      ];

      // Don't use ...$info: keys can be out of order.
      $this->clients[$alias] = new Client($info['uri'], $info['uriOptions'], $info['driverOptions']);
    }
    return $this->clients[$alias];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ClientFactory::$clients protected property A hash of connections per alias.
ClientFactory::$settings protected property The 'mongodb' client settings.
ClientFactory::get public function Return a Client instance for a given alias.
ClientFactory::__construct public function Constructor.