php-doc-en/reference/mongo/mongoclient/construct.xml
2015-11-19 13:46:44 +00:00

841 lines
28 KiB
XML

<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xml:id="mongoclient.construct" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<refnamediv>
<refname>MongoClient::__construct</refname>
<refpurpose>Creates a new database connection object</refpurpose>
</refnamediv>
<refsynopsisdiv role="soft-deprecation-notice">
<sidebar>
&mongo.alternative.method.note;
<simplelist role="alternatives">
<member><methodname>MongoDB\Driver\Manager::__construct</methodname></member>
</simplelist>
</sidebar>
</refsynopsisdiv>
<refsect1 role="description">
&reftitle.description;
<constructorsynopsis>
<modifier>public</modifier> <methodname>MongoClient::__construct</methodname>
<methodparam choice="opt"><type>string</type><parameter>server</parameter><initializer>"mongodb://localhost:27017"</initializer></methodparam>
<methodparam choice="opt"><type>array</type><parameter>options</parameter><initializer>array("connect" => &true;)</initializer></methodparam>
<methodparam choice="opt"><type>array</type><parameter>driver_options</parameter></methodparam>
</constructorsynopsis>
<para>
If no parameters are passed, this connects to "localhost:27017" (or whatever
was specified in php.ini for
<link linkend="ini.mongo.default-host">mongo.default_host</link> and
<link linkend="ini.mongo.default-port">mongo.default_port</link>).
</para>
<para>
<parameter>server</parameter> should have the form:
<programlisting role="txt">
<![CDATA[
mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
]]>
</programlisting>
</para>
<para>
The connection string always starts with <literal>mongodb://</literal>, to
indicate it is a connection string in this form.
</para>
<para>If <literal>username</literal> and <literal>password</literal>
are specified, the constructor will attempt to authenticate the connection
with the database before returning. Username and password are optional
and must be followed by an <literal>@</literal>, if specified.
</para>
<para>
At least one host must be given (port optional, always defaulting to 27017)
and as many hosts as desired may be connected to. Host names are
comma-separated and the constructor will return successfully if it connected
to at least one host. If it could not connect to any of the hosts, it will
throw a <classname>MongoConnectionException</classname>. Please see the
<link linkend="mongo.connecting.rs">Replica Sets</link> section for
information on how to connect to Replica Sets.
</para>
<para>
If you specified a username and password, you may specify a database to
authenticate with. If <literal>db</literal> is not specified, "admin" will
be used.
</para>
<para>
An optional query string may be used to specify extra options. The same
options are supported through the <parameter>options</parameter> array as
well, and are therefore redescribed there. See the <link
linkend="mongo.mongoclient.construct.examples">examples below</link> on
how to set those options.
</para>
<para>
One part of the options governs how the driver reads from secondary nodes
in a replica set environment. Extra information on how these read
preferences work is available as well through the <link
linkend="mongo.readpreferences">read preferences</link> documentation page.
</para>
</refsect1>
<refsect1 role="parameters" xml:id="mongo.mongoclient.construct.parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term>
<parameter>server</parameter>
</term>
<listitem>
<para>
The server name.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>options</parameter>
</term>
<listitem>
<para>
An array of options for the connection. Currently available options
include:
<itemizedlist>
<listitem>
<para>
<literal>"authMechanism"</literal>
</para>
<para>
Available mechanisms are:
<informaltable>
<tgroup cols="3">
<thead>
<row>
<entry>authMechanism</entry>
<entry>Description</entry>
<entry>Availability</entry>
</row>
</thead>
<tbody>
<row>
<entry>MONGODB-CR</entry>
<entry>Authenticate using Challenge Response mechanism. This is the default value.</entry>
<entry>All MongoDB versions</entry>
</row>
<row>
<entry>X509</entry>
<entry>Authenticates using X509 certificates</entry>
<entry>MongoDB 2.6. Only available when <xref linkend="book.openssl" /> is enabled</entry>
</row>
<row>
<entry>PLAIN</entry>
<entry>Authenticates using unencrypted plain username+password. Must be used over SSL connections. Generally used by MongoDB to login via 3rd party LDAP server</entry>
<entry>MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2</entry>
</row>
<row>
<entry>GSSAPI</entry>
<entry>Authenticates via kerberos systems</entry>
<entry>MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</listitem>
<listitem>
<para>
<literal>"authSource"</literal>
</para>
<para>
Should be set to the database name where the user is defined it.
</para>
</listitem>
<listitem>
<para>
<literal>"connect"</literal>
</para>
<para>
If the constructor should connect before returning. Default is
&true;. When set to &false; the driver will
<emphasis>automatically</emphasis> connect to the server whenever
it is necessary to do a query. Alternatively, you can run
<function>MongoClient::connect</function> manually.
</para>
<warning>
<para>
This option is not supported through the connection string.
</para>
</warning>
</listitem>
<listitem>
<para>
<literal>"connectTimeoutMS"</literal>
</para>
<para>
How long a connection can take to be opened before timing out in
milliseconds. Defaults to <literal>60000</literal> (60 seconds).
</para>
<para>
If <literal>-1</literal> is specified, no connection timeout will be
applied and PHP will use
<link linkend="ini.default-socket-timeout">default_socket_timeout</link>.
</para>
</listitem>
<listitem>
<para>
<literal>"db"</literal>
</para>
<para>
The database to authenticate against can be specified here, instead of
including it in the host list. This overrides a database given in the
host list.
</para>
</listitem>
<listitem>
<para>
<literal>"fsync"</literal>
</para>
<para>
When <literal>"fsync"</literal> is set, all write operations will
block until the database has flushed the changes to disk. This makes
the write operations slower, but it guarantees that writes have
succeeded and that the operations can be recovered in case of total
system failure.
</para>
<para>
If the MongoDB server has journaling enabled, this option is identical
to <emphasis>"journal"</emphasis>. If journaling is not enabled, this
option ensures that write operations will be synced to database files
on disk.
</para>
<note>
<simpara>
If journaling is enabled, users are strongly encouraged to use the
<literal>"journal"</literal> option instead of
<literal>"fsync"</literal>. Do not use <literal>"fsync"</literal> and
<literal>"journal"</literal> simultaneously, as that will result in
an error.
</simpara>
</note>
</listitem>
<listitem>
<para>
<literal>"journal"</literal>
</para>
<para>
When <literal>"journal"</literal> is set, all write operations will
block until the database has flushed the changes to the journal on
disk. This makes the write operations slower, but it guarantees that
writes have succeeded and that the operations can be recovered in case
of total system failure.
</para>
<note>
<simpara>
If this option is used and journaling is disabled, MongoDB 2.6+ will
raise an error and the write will fail; older server versions will
simply ignore the option.
</simpara>
</note>
</listitem>
<listitem>
<para>
<literal>"gssapiServiceName"</literal>
</para>
<para>
Sets the <link xlink:href="&url.mongodb.docs.kerberos.service-principal;">Kerberos service principal</link>. Only applicable when authMechanism=GSSAPI. Defaults to "mongodb".
</para>
</listitem>
<listitem>
<para>
<literal>"password"</literal>
</para>
<para>
The password can be specified here, instead of including it in the
host list. This is especially useful if a password has a "@" in it.
This overrides a password set in the host list.
</para>
</listitem>
<listitem>
<para>
<literal>"readPreference"</literal>
</para>
<para>
Specifies the read preference type. Read preferences provide you
with control from which secondaries data can be read from.
</para>
<para>
Allowed values are: <constant>MongoClient::RP_PRIMARY</constant>,
<constant>MongoClient::RP_PRIMARY_PREFERRED</constant>,
<constant>MongoClient::RP_SECONDARY</constant>,
<constant>MongoClient::RP_SECONDARY_PREFERRED</constant> and
<constant>MongoClient::RP_NEAREST</constant>.
</para>
<para>
See the documentation on <link linkend="mongo.readpreferences">read
preferences</link> for more information.
</para>
</listitem>
<listitem>
<para>
<literal>"readPreferenceTags"</literal>
</para>
<para>
Specifies the read preference tags as an array of strings. Tags can be
used in combination with the <literal>readPreference</literal> option
to further control which secondaries data might be read from.
</para>
<para>
See the documentation on <link linkend="mongo.readpreferences">read
preferences</link> for more information.
</para>
</listitem>
<listitem>
<para>
<literal>"replicaSet"</literal>
</para>
<para>
The name of the replica set to connect to. If this is given, the
primary will be automatically be determined. This means that the
driver may end up connecting to a server that was not even listed.
See the replica set example below for details.
</para>
</listitem>
<listitem>
<para>
<literal>"secondaryAcceptableLatencyMS"</literal>
</para>
<para>
When reading from a secondary (using ReadPreferences), do not read from secondaries known to be more then
<literal>secondaryAcceptableLatencyMS</literal> away from us. Defaults to <literal>15</literal>
</para>
</listitem>
<listitem>
<para>
<literal>"socketTimeoutMS"</literal>
</para>
<para>
How long a socket operation (read or write) can take before timing out
in milliseconds. Defaults to <literal>30000</literal> (30 seconds).
</para>
<para>
If <literal>-1</literal> is specified, socket operations may block
indefinitely. This option may also be set on a per-operation basis
using <methodname>MongoCursor::timeout</methodname> for queries or the
<literal>"socketTimeoutMS"</literal> option for write methods.
</para>
<note>
<simpara>
This is a client-side timeout. If a write operation times out, there
is no way to know if the server actually handled the write or not, as
a <classname>MongoCursorTimeoutException</classname> will be thrown
in lieu of returning a write result.
</simpara>
</note>
</listitem>
<listitem>
<para>
<literal>"ssl"</literal>
</para>
<para>
A boolean to specify whether you want to enable SSL for the
connections to MongoDB. Extra options such as certificates
can be set with <xref linkend="context.ssl" />.
</para>
</listitem>
<listitem>
<para>
<literal>"username"</literal>
</para>
<para>
The username can be specified here, instead of including it in the
host list. This is especially useful if a username has a ":" in it.
This overrides a username set in the host list.
</para>
</listitem>
<listitem>
<para>
<literal>"w"</literal>
</para>
<para>
The <literal>w</literal> option specifies the
<link linkend="mongo.writeconcerns">Write Concern</link> for the driver,
which determines how long the driver blocks when writing. The
default value is <literal>1</literal>.
</para>
<para>
This option is applicable when connecting to both single servers and
replica sets. A positive value controls how <emphasis>many</emphasis>
nodes must acknowledge the write instruction before the driver
continues. A value of <literal>1</literal> would require the single
server or primary (in a replica set) to acknowledge the write
operation. A value of <literal>3</literal> would cause the driver to
block until the write has been applied to the primary as well as two
secondary servers (in a replica set).
</para>
<para>
A string value is used to control which tag sets are taken into
account for write concerns. <literal>"majority"</literal> is special
and ensures that the write operation has been applied to the majority
(more than 50%) of the participating nodes.
</para>
</listitem>
<listitem>
<para>
<literal>"wTimeoutMS"</literal>
</para>
<para>
This option specifies the time limit, in milliseconds, for
<link linkend="mongo.writeconcerns">write concern</link>
acknowledgement. It is only applicable for write operations where
<literal>"w"</literal> is greater than <literal>1</literal>, as the
timeout pertains to replication. If the write concern is not satisfied
within the time limit, a <classname>MongoCursorException</classname>
will be thrown. A value of <literal>0</literal> may be specified to
block indefinitely. The default value is <literal>10000</literal>
(ten seconds).
</para>
</listitem>
</itemizedlist>
</para>
<para>
The following options are deprecated and should no longer be used:
<itemizedlist>
<listitem>
<para>
<literal>"slaveOkay"</literal>
</para>
<para>
Deprecated. Please use the <link linkend="mongo.readpreferences">read
preference</link> options.
</para>
</listitem>
<listitem>
<para>
<literal>"timeout"</literal>
</para>
<para>
Deprecated alias for <literal>"connectTimeoutMS"</literal>.
</para>
</listitem>
<listitem>
<para>
<literal>"wTimeout"</literal>
</para>
<para>
Deprecated alias for <literal>"wTimeoutMS"</literal>.
</para>
</listitem>
</itemizedlist>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>driver_options</parameter>
</term>
<listitem>
<para>
An array of options for the MongoDB driver. Options include setting
connection <link linkend="mongo.connecting.context.ssl">context options for SSL</link>
or <link linkend="context.mongodb">logging callbacks</link>.
<itemizedlist>
<listitem>
<para>
<literal>"context"</literal>
</para>
<para>
The Stream Context to attach to all new connections. This allows you
for example to configure SSL certificates and are described at
<link linkend="context.ssl">SSL context options</link>. See the
<link linkend="mongo.connecting.context.ssl">Connecting over SSL</link> tutorial.
</para>
</listitem>
</itemizedlist>
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns a new database connection object.
</para>
</refsect1>
<refsect1 role="errors">
&reftitle.errors;
<para>
Throws <classname>MongoConnectionException</classname> if it tries and fails
to connect to the database for all hostnames given. It will also throw a
<classname>MongoConnnectionException</classname> if an invalid username or
password is given. See <classname>MongoConnectionException</classname>
documentation for common exceptions and their causes.
</para>
</refsect1>
<refsect1 role="examples" xml:id="mongo.mongoclient.construct.examples">
&reftitle.examples;
<example>
<title><function>MongoClient::__construct</function> replica set example</title>
<para>
This example shows how to connect the driver to a replica set. It assumes
that there is a set of three servers: sf1.example.com, sf2.example.com, and
ny1.example.com. The primary could be any one of these servers.
</para>
<programlisting role="php">
<![CDATA[
<?php
// pass a comma-separated list of server names to the constructor
// Note that we don't need to pass in all the members of the replicaset, the driver
// will derive the full list.
$m1 = new MongoClient("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));
?>
]]>
</programlisting>
<para>
If the current primary fails, the driver will figure out which secondary
server became the new primary and automatically start using that connection.
Automatic failover will not work correctly if <literal>replicaSet</literal>
is not specified.
</para>
<para>
At least one seed in the seed list must be up for the driver to connect to
the replica set.
</para>
<para>
If you include seeds from two separate replica sets, behavior is undefined.
</para>
<para>See the
<link xlink:href="&url.mongodb.dochub.rs;">core documentation</link> on
replica sets for more information.
</para>
</example>
<example>
<title>Connecting to a domain socket</title>
<para>
In version 1.0.9+, you can use a UNIX domain socket to connect to an
instance of MongoDB running locally. This should be slightly faster than
using a network connection.
</para>
<para>
In version 1.5.0, the MongoDB server automatically opens a socket at
/tmp/mongodb-&lt;port&gt;.sock. You can connect to this by specifying the
path in your connection string:
</para>
<programlisting role="php">
<![CDATA[
<?php
// MongoDB server running locally on port 20000
$m = new MongoClient("mongodb:///tmp/mongodb-20000.sock");
?>
]]>
</programlisting>
<para>
You can combine this with any other connections you'd like:
</para>
<programlisting role="php">
<![CDATA[
<?php
// try to connect to the domain socket, fall back to localhost connection
$m = new MongoClient("mongodb:///tmp/mongodb-27017.sock,localhost:27017");
?>
]]>
</programlisting>
</example>
<example>
<title><function>MongoClient::__construct</function> authentication example</title>
<para>
A user must exist in the admin database before attempting to use
authentication. You can create one with the Mongo shell by running:
</para>
<programlisting role="shell">
<![CDATA[
> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
"_id" : ObjectId("4b21272fd9ab21611d19095c"),
"user" : "testUser",
"pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>
]]>
</programlisting>
<para>
After creating a user with, in this case, username "testUser" and password
"testPass", you can create an authenticated connection:
</para>
<programlisting role="php">
<![CDATA[
<?php
$m = new MongoClient("mongodb://testUser:testPass@localhost");
?>
]]>
</programlisting>
</example>
<example>
<title><function>MongoClient::__construct</function> read preference example</title>
<programlisting role="php">
<![CDATA[
<?php
// Prefer the nearest server in the "east" data center
$uri = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>
]]>
</programlisting>
<para>
See the <link linkend="mongo.readpreferences">read preferences</link>
section of this manual for further information.
</para>
</example>
<example>
<title><function>MongoClient::__construct</function> options example</title>
<para>
Options can be passed both through the query string in the connection
string, or as an array passed as second argument to the constructor.
</para>
<para>
Here we set the journal option to true and readPreference to secondary
preferred as default for all write operations:
</para>
<programlisting role="php">
<![CDATA[
<?php
$m = new MongoClient("mongodb://localhost/?journal=true&readPreference=secondary");
?>
]]>
</programlisting>
<para>
And now we do the same, but as an options array:
</para>
<programlisting role="php">
<![CDATA[
<?php
$options = array(
'journal' => true,
'readPreference' => 'secondary',
);
$m = new MongoClient("mongodb://localhost/", $options);
?>
]]>
</programlisting>
</example>
<example>
<title><function>MongoClient::__construct</function> read preference example</title>
<programlisting role="php">
<![CDATA[
<?php
// Prefer the nearest server in the "east" data center
$uri = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>
]]>
</programlisting>
<para>
See the <link linkend="mongo.readpreferences">read preferences</link>
section of this manual for further information.
</para>
</example>
</refsect1>
<refsect1 role="changelog">
&reftitle.changelog;
<para>
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>&Version;</entry>
<entry>&Description;</entry>
</row>
</thead>
<tbody>
<row>
<entry>1.5.0</entry>
<entry>
<para>
Added <literal>"authMechanism"</literal>, <literal>"gssapiServiceName"</literal>, and <literal>"secondaryAcceptableLatencyMS"</literal>.
</para>
</entry>
</row>
<row>
<entry>1.4.0</entry>
<entry>
<para>
Added <literal>"ssl"</literal> option and support for
<link linkend="mongo.connecting.ssl">connecting over SSL</link>.
</para>
<para>
Added <literal>"wTimeoutMS"</literal> option, which replaces
<literal>"wTimeout"</literal>.
</para>
<para>
Emits <constant>E_DEPRECATED</constant> when
<literal>"slaveOkay"</literal> or <literal>"timeout"</literal> is used.
</para>
</entry>
</row>
<row>
<entry>1.5.0</entry>
<entry>
<para>
Added <literal>"authSource"</literal>.
</para>
</entry>
</row>
<row>
<entry>1.3.4</entry>
<entry>
<para>
Added <literal>"connectTimeoutMS"</literal> and
<literal>"socketTimeoutMS"</literal> options.
</para>
</entry>
</row>
<row>
<entry>1.3.0</entry>
<entry>
<para>
Added <literal>"readPreference"</literal>,
<literal>"readPreferenceTags"</literal>, <literal>"w"</literal>, and
<literal>"wTimeout"</literal> options.
</para>
</entry>
</row>
<row>
<entry>1.2.0</entry>
<entry>
<para>
Added <literal>"username"</literal> and <literal>"password"</literal>
options.
</para>
<para>
Removed <literal>"persist"</literal> option, as all connections are
now persistent. It can still be used, but it doesn't affect anything.
</para>
<variablelist>
<varlistentry>
<term>
<parameter>"persist"</parameter>
</term>
<listitem>
<para>
If the connection should be persistent. If set, the connection will
be persistent. The string representation of the value is used as an
ID for the connection, so two instances of
<classname>MongoClient</classname> that are initialized with
<literal>array("persist" => "foobar")</literal> will share the same
database connection, whereas an instance initialized with
<literal>array("persist" => "barbaz")</literal> will use a different
database connection.
</para>
</listitem>
</varlistentry>
</variablelist>
<para>
The <literal>"replicaSet"</literal> option now takes a string, not a
boolean.
</para>
</entry>
</row>
<row>
<entry>1.0.9</entry>
<entry>Added <literal>"replicaSet"</literal> option.</entry>
</row>
<row>
<entry>1.0.2</entry>
<entry>
<para>
Changed constructor to take an array of options. Pre-1.0.2, the
constructor took the following parameters:
</para>
<variablelist>
<varlistentry>
<term>
<parameter>server</parameter>
</term>
<listitem>
<para>
The server name.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>connect</parameter>
</term>
<listitem>
<para>
Optional boolean parameter specifying if the constructor should
connect to the database before returning. Defaults to &true;.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>persistent</parameter>
</term>
<listitem>
<para>
If the connection should be persistent.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>paired</parameter>
</term>
<listitem>
<para>
If the connection should be paired.
</para>
</listitem>
</varlistentry>
</variablelist>
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->