==============================
MongoDB\\Client::__construct()
==============================

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

.. phpmethod:: MongoDB\Client::__construct()

   Constructs a new :phpclass:`Client <MongoDB\Client>` instance.

   .. code-block:: php

      function __construct(
          ?string $uri = null,
          array $uriOptions = [],
          array $driverOptions = []
      )

Parameters
----------

``$uri`` : string
  The MongoDB connection string. Refer to
  :manual:`Connection Strings </reference/connection-string>` in the MongoDB
  manual for more information.

  Defaults to ``"mongodb://127.0.0.1:27017"`` if unspecified.

  Any special characters in the URI components need to be encoded according to
  `RFC 3986 <https://www.rfc-editor.org/info/rfc3986>`_. This is particularly
  relevant to the username and password, which can often include special
  characters such as ``@``, ``:``, or ``%``. When connecting via a Unix domain
  socket, the socket path may contain special characters such as slashes and
  must be encoded. The :php:`rawurlencode() <rawurlencode>` function may be used
  to encode constituent parts of the URI.

``$uriOptions`` : array
  Specifies additional URI options, such as authentication credentials or query
  string parameters. The options specified in ``$uriOptions`` take precedence
  over any analogous options present in the ``$uri`` string and do not need to
  be encoded according to `RFC 3986 <https://www.rfc-editor.org/info/rfc3986>`_.

  Refer to the :php:`MongoDB\Driver\Manager::__construct()
  <mongodb-driver-manager.construct>` extension documentation for a list of
  supported options.

``$driverOptions`` : array
  Specifies options specific to the PHP driver. In addition to driver options
  supported by the :php:`extension <mongodb-driver-manager>`, the library
  additionally supports specifying a default 
  :php:`type map <manual/en/mongodb.persistence.deserialization.php#mongodb.persistence.typemaps>`
  to apply to the cursors it creates.

  .. list-table::
     :header-rows: 1
     :widths: 20 20 80

     * - Name
       - Type
       - Description

     * - autoEncryption
       - array
       - Options to configure client-side field-level encryption in the driver.
         Refer to the
         :php:`extension documentation <manual/en/mongodb-driver-manager.construct.php#mongodb-driver-manager.construct-driveroptions>`
         for a list of supported encryption options.

         If a :phpclass:`MongoDB\Client` is provided for the ``keyVaultClient``
         option, it will be unwrapped into a
         :php:`MongoDB\Driver\Manager <class.mongodb-driver-manager>` for the
         extension.

         .. versionadded:: 1.6

     * - driver
       - array
       - Additional driver metadata to be passed on to the server handshake.
         This is an array containing ``name``, ``version``, and ``platform``
         string fields. For example:

         .. code-block:: php

            [
                'name' => 'my-driver',
                'version' => '1.2.3-dev',
                'platform' => 'some-platform',
            ]

         .. note::

            This feature is primarily designed for custom drivers and ODMs,
            which may want to identify themselves to the server for diagnostic
            purposes. Applications wishing to identify themselves should use the
            ``appName`` URI option instead of this option.

         .. versionadded:: 1.7

     * - serverApi
       - :php:`MongoDB\Driver\ServerApi <class.mongodb-driver-serverapi>`
       - Used to declare an API version on the client. Refer to the
         :manual:`Stable API </reference/stable-api>` page in the Server manual for
         additional information.

         .. versionadded:: 1.9

     * - typeMap
       - array
       - Default :php:`type map <manual/en/mongodb.persistence.deserialization.php#mongodb.persistence.typemaps>`
         to apply to cursors, which determines how BSON documents are converted
         to PHP values. The library uses the following type map by default:

         .. code-block:: php

            [
                'array' => 'MongoDB\Model\BSONArray',
                'document' => 'MongoDB\Model\BSONDocument',
                'root' => 'MongoDB\Model\BSONDocument',
            ]

     * - allow_invalid_hostname
       - boolean
       - Disables hostname validation if ``true``. Defaults to ``false``.

         Allowing invalid hostnames may expose the driver to a
         `man-in-the-middle attack <https://en.wikipedia.org/wiki/Man-in-the-middle_attack>`__.

         .. deprecated:: 1.6

            This option has been deprecated. Use the
            ``tlsAllowInvalidHostnames`` URI option instead.

     * - ca_dir
       - string
       - Path to a correctly hashed certificate directory. The system
         certificate store will be used by default.

         Falls back to the deprecated ``capath`` SSL context option if not
         specified.

     * - ca_file
       - string
       - Path to a certificate authority file. The system certificate store will
         be used by default.

         Falls back to the deprecated ``cafile`` SSL context option if not
         specified.

         .. deprecated:: 1.6

            This option has been deprecated. Use the ``tlsCAFile`` URI option
            instead.

     * - crl_file
       - string
       - Path to a certificate revocation list file.

     * - pem_file
       - string
       - Path to a PEM encoded certificate to use for client authentication.

         Falls back to the deprecated ``local_cert`` SSL context option if not
         specified.

         .. deprecated:: 1.6

            This option has been deprecated. Use the ``tlsCertificateKeyFile``
            URI option instead.

     * - pem_pwd
       - string
       - Passphrase for the PEM encoded certificate (if applicable).

         Falls back to the deprecated ``passphrase`` SSL context option if not
         specified.

         .. deprecated:: 1.6

            This option has been deprecated. Use the
            ``tlsCertificateKeyFilePassword`` URI option instead.

     * - weak_cert_validation
       - boolean
       - Disables certificate validation ``true``. Defaults to ``false``.

         Falls back to the deprecated ``allow_self_signed`` SSL context option
         if not specified.

         .. deprecated:: 1.6

            This option has been deprecated. Use the
            ``tlsAllowInvalidCertificates`` URI option instead.

     * - context
       - resource
       - :php:`SSL context options <manual/en/context.ssl.php>` to be used as
         fallbacks for other driver options (as specified). Note that the driver
         does not consult the default stream context.

         This option is supported for backwards compatibility, but should be
         considered deprecated.

Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

Behavior
--------

A :php:`MongoDB\Driver\Manager <mongodb-driver-manager>` is constructed
internally. Per the `Server Discovery and Monitoring
<https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#single-threaded-client-construction>`_
specification, :php:`MongoDB\Driver\Manager::__construct()
<mongodb-driver-manager.construct>` performs no I/O. Connections will be
initialized on demand, when the first operation is executed.

Examples
--------

.. start-connecting-include

Connecting to a Standalone server
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you do not specify a ``$uri`` value, the driver connects to a standalone
:program:`mongod` on ``127.0.0.1`` via port ``27017``. To connect to a different
server, pass the corresponding connection string as the first parameter when
creating the :phpclass:`Client <MongoDB\Client>` instance:

.. code-block:: php

   <?php

   $client = new MongoDB\Client('mongodb://mongodb-deployment:27017');

Connecting to a Replica Set
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following example demonstrates how to connect to a replica set with a custom
read preference:

.. code-block:: php

   <?php

   $client = new MongoDB\Client(
       'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet',
       [
           'readPreference' => 'secondaryPreferred',
       ]
   );

Connecting with SSL and Authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following example demonstrates how to connect to a MongoDB replica set with
SSL and authentication, as is used for `MongoDB Atlas
<https://cloud.mongodb.com/?jmp=docs>`_:

.. code-block:: php

   <?php

   $client = new MongoDB\Client(
       'mongodb://myUsername:myPassword@rs1.example.com,rs2.example.com/?ssl=true&replicaSet=myReplicaSet&authSource=admin'
   );

Alternatively, the authentication credentials and URI parameters may be
specified in the constructor's ``$uriOptions`` parameter:

.. code-block:: php

   <?php

   $client = new MongoDB\Client(
       'mongodb://rs1.example.com,rs2.example.com/'
       [
           'username' => 'myUsername',
           'password' => 'myPassword',
           'ssl' => true,
           'replicaSet' => 'myReplicaSet',
           'authSource' => 'admin',
       ],
   );

The driver supports additional :php:`SSL options
<mongodb-driver-manager.construct#mongodb-driver-manager.construct-driveroptions>`,
which may be specified in the constructor's ``$driverOptions`` parameter. Those
options are covered in the :php:`MongoDB\Driver\Manager::__construct()
<mongodb-driver-manager.construct>` documentation.

.. end-connecting-include

Specifying a Custom Type Map
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

By default, the |php-library| deserializes BSON documents and arrays
as :phpclass:`MongoDB\Model\BSONDocument` and
:phpclass:`MongoDB\Model\BSONArray` objects, respectively. The following
example demonstrates how to have the library unserialize everything as a PHP
array, as was done in the legacy ``mongo`` extension.

.. code-block:: php

   <?php

   $client = new MongoDB\Client(
       null,
       [],
       [
           'typeMap' => [
               'root' => 'array',
               'document' => 'array',
               'array' => 'array',
           ],
       ]
   );

See Also
--------

- :php:`MongoDB\Driver\Manager::__construct()
  <mongodb-driver-manager.construct>`
- :manual:`Connection String URI Format </reference/connection-string>` in the
  MongoDB manual
- `Server Discovery and Monitoring
  <https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#single-threaded-client-construction>`_
  specification
