liquidbox/silex-mongodb

A MongoDB service provider for the Silex micro-framework

dev-master 2018-01-04 09:53 UTC

README

GitHub release license Build Status Code Coverage Scrutinizer Code Quality Packagist

You are reading the documentation for Silex 2.x. Switch to the documentation for Silex 1.x.

MongoDB

The MongoDbServiceProvider provides integration with the MongoDB extension.

Parameters

  • mongodb.uri (optional): A MongoDB connection URI.
  • mongodb.connection (optional): A collection of parameters for specifying the connection string.
    • host (optional): The server address to connect to. Identifies either a hostname, IP address, or UNIX domain socket.
    • port (optional): The default value is 27017.
    • username (optional): The username for the connection string.
    • password (optional): The password for the connection string.
    • database (optional): The name of the database.
    • options (optional): A collection of connection specific options. See Connection String Options for a full description of these options.
  • mongodb.uri_options (optional): Additional connection string options, which will overwrite any options with the same name in the uri or connection parameter.
  • mongodb.driver_options (optional): An array of options for the MongoDB driver.

The uri parameter overrides connection.

Services

  • mongodb: The MongoDB\Client connection instance. The main way of interacting with MongoDB.
  • mongodb.clients: The collection of MongoDB client instances. See section on using multiple clients for details.
  • mongodb.client: Factory for MongoDB\Client connection instances.

Registering

Example #1 Connecting to a replica set named test

$app->register(new \LiquidBox\Silex\Provider\MongoDbServiceProvider(), array(
    'mongodb.uri' => "mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test",
));

// or

$app->register(new \LiquidBox\Silex\Provider\MongoDbServiceProvider(), array(
    'mongodb.connection' => "db1.example.net:27017,db2.example.net:2500/?replicaSet=test",
));

// or

$app->register(new \LiquidBox\Silex\Provider\MongoDbServiceProvider(), array(
    'mongodb.connection' => array(
        'hosts' => array(
            "db1.example.net:27017",
            array(
                'host' => "db2.example.net",
                'port' => 2500
            ),
        ),
        'options' => array(
            'replicaSet' => "test",
        )
    ),
));

All the registered connections above are equivalent.

Example #2 Connecting to a sharded cluster

$app->register(new \LiquidBox\Silex\Provider\MongoDbServiceProvider(), array(
    'mongodb.connection' => "r1.example.net:27017,r2.example.net:27017",
));

// or

$app->register(new \LiquidBox\Silex\Provider\MongoDbServiceProvider(), array(
    'mongodb.connection' => array(
        'hosts' => array(
            array('host' => "r1.example.net", 'port' => 27017),
            array('host' => "r2.example.net", 'port' => 27017),
        ),
    ),
));

Example #3 Connecting to a UNIX domain socket with file path /tmp/mongodb-27017.sock

$app->register(new \LiquidBox\Silex\Provider\MongoDbServiceProvider(), array(
    'mongodb.connection' => rawurlencode("/tmp/mongodb-27017.sock"),
));

Add MongoDB as a dependency:

composer require liquidbox/silex-mongodb:^2.0

Usage

Example #1: Inserting a document into the beers collection of the demo database

$collection = $app['mongodb']->demo->beers;

$result = $collection->insertOne(array(
    'name'    => "Hinterland",
    'brewery' => "BrewDog",
));

echo "Inserted with Object ID '{$result->getInsertedId()}'";

Example #2: Using the find method

$collection = $app['mongodb']->demo->beers;

$results = $collection->find(array(
    'name'    => "Hinterland",
    'brewery' => "BrewDog",
));

foreach ($results as $entry) {
    printf('%d: %s' . PHP_EOL, $entry['_id'], $entry['name']);
}

Using multiple clients

The MongoDB provider can allow the use of multiple clients. In order to configure the URIs, use mongodb.uri as an array of configurations where keys are connection names and values are parameters:

$config['mongodb']['replica_name']    = "test";
$config['mongodb']['replica_cluster'] = array(
    "example1.com",
    "example2.com",
    "example3.com",
);

// ...

$app->register(new LiquidBox\Silex\Provider\MongoDbServiceProvider(), array(
    'mongodb.uri' => array(
        'mongo_read' => array(
            'connection' => array(
                'hosts'   => $config['mongodb']['replica_cluster'],
                'options' => array(
                    'replicaSet'     => $config['mongodb']['replica_name'],
                    'readPreference' => "secondary",
                )
            ),
        ),
        'mongo_write' => array(
            'connection' => array(
                'hosts'   => $config['mongodb']['replica_cluster'],
                'options' => array(
                    'replicaSet' => $config['mongodb']['replica_name'],
                    'w'          => 2
                    'wtimeoutMS' => 2000,
                )
            ),
        ),
    ),
));

The first registered connection is the default and can simply be accessed as you would if there was only one connection. Given the above configuration, these two lines are equivalent:

$app['mongodb']->zips->find(array('city' => "JERSEY CITY", 'state' => "NJ"));

$app['mongodb.clients']['mongo_read']->zips->find(array('city' => "JERSEY CITY", 'state' => "NJ"));

For more information, check out the official MongoDB documentation.