PHPackages                             corllete/silex-mongodb-provider - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. corllete/silex-mongodb-provider

ActiveLibrary[Database &amp; ORM](/categories/database)

corllete/silex-mongodb-provider
===============================

Silex 2.x MongoDB Service Provider - MongoDB PHP Library

v1.1.0(9y ago)69.3kMITPHPPHP ~5.6||~7.0

Since Sep 4Pushed 9y ago2 watchersCompare

[ Source](https://github.com/corllete/silex-mongodb-provider)[ Packagist](https://packagist.org/packages/corllete/silex-mongodb-provider)[ RSS](/packages/corllete-silex-mongodb-provider/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (3)Dependencies (3)Versions (4)Used By (0)

silex-mongodb-provider
======================

[](#silex-mongodb-provider)

[![Build Status](https://camo.githubusercontent.com/6d354b22fba01588aaf9caeb3393d6ba8f6e3de01fdee08affd10b5e81297905/68747470733a2f2f7472617669732d63692e6f72672f636f726c6c6574652f73696c65782d6d6f6e676f64622d70726f76696465722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/corllete/silex-mongodb-provider)[![codecov](https://camo.githubusercontent.com/b200e96e93c444c36acd779b3066e43b4f7131205517965648670e9df617b943/68747470733a2f2f636f6465636f762e696f2f67682f636f726c6c6574652f73696c65782d6d6f6e676f64622d70726f76696465722f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/corllete/silex-mongodb-provider)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/832b1b9d55021112dc9e8ba3e01b578d980e1a854beb9aba2eeabb3afefa60f8/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f636f726c6c6574652f73696c65782d6d6f6e676f64622d70726f76696465722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/corllete/silex-mongodb-provider/?branch=master)

Silex MongoDB Service Provider - integrates [Mongo PHP Library](https://github.com/mongodb/mongo-php-library)with [Silex 2.x](https://github.com/silexphp/Silex)

Requirements
------------

[](#requirements)

- PHP 5.6+ || 7.0+
- php-mongodb (ext-mongodb)
- Silex 2.x

Installation
------------

[](#installation)

```
$ composer require "corllete/silex-mongodb-provider=^1.0.0"

```

Configuration &amp; Usage
-------------------------

[](#configuration--usage)

Connection uri defaults to `mongodb://localhost:27017`. For additional resources about configuration/setup options and library usage, take a look at the [Resources section](#resources).

### Zero Configuration

[](#zero-configuration)

**Container setup**

```
use Corllete\SilexMongoDB\Provider\MongoDBServiceProvider;

// connection uri: mongodb://localhost:27017
$app->register(new MongoDBServiceProvider());
```

> NOTE!
>
> I omit `use Corllete\SilexMongoDB\Provider\MongoDBServiceProvider;` line in all of the examples below for a sake of simplicity.

**Usage**

```
/** @var $mongo \MongoDB\Client */
$mongo = $app['mongodb'];

// Instance of MongoDB\Database
$database = $mongo->some_db;

// Instance of MongoDB\Collection
$collection = $mongo->some_collection;

// OR the short version
$collection = $app['mongodb']->some_db->some_collection

// Instance of MongoDB\InsertOneResult
$result = $collection->insertOne([
    'name' => 'Gandalf The White'
]);

printf("Inserted %d document(s)\n", $result->getInsertedCount());
// Outputs: Inserted 1 document(s)

// Instance of MongoDB\BSON\ObjectID
$insertedId = $result->getInsertedId();

// Instance of MongoDB\Model\BSONDocument
$document = $collection->findOne(['_id' => $insertedId]);

echo $document['name'];
// 'Gandalf The White'

// Do your ninja magic here!
```

### Provide some options

[](#provide-some-options)

**Container setup**

```
// connection uri: mongodb://example.com:27017
$app->register(new MongoDBServiceProvider(), [
    'mongodb.options' => [
        'uri' => 'mongodb://example.com:27017',
        'uri_options'    => [...],
        'driver_options' => [
            'type_map' => [...],
        ],
    ],
]);
```

**Usage**

```
/** @var $collection \MongoDB\Collection */
$collection = $app['mongodb']->db->collection;
```

### Multiple Connections

[](#multiple-connections)

**Container setup**

```
// `first` is the default connection, living in $app['mongodb'] namespace
$app->register(new MongoDBServiceProvider(), [
    'mongodbs.options' => [
        'first' => [
            'uri' => 'mongodb://first.com:27017',
        ],
        'second' => [
            'uri' => 'mongodb://user:pass@second.com:27017/some_db',
        ],
        'third' => [
            'uri' => 'mongodb://third.com:27017,mongodb://third.com:27018?replicaSet=myReplica',
        ],
    ],
]);
```

> **WARNING!**
>
> You have to apply `rawurlencode()` username and password when used directly in the uri string

**Usage**

```
// mongodb://first.com:27017
$first = $app['mongodb'];

// OR
$first = $app['mongodbs']['first'];

// OR even
$first = $app['mongodbs']['default'];

// 'second' connection
$second = $app['mongodbs']['second'];

// 'third' connection
$second = $app['mongodbs']['third'];

// Do your ninja magic here!
```

### Explicit set default connection via connection name reference

[](#explicit-set-default-connection-via-connection-name-reference)

**Container setup**

```
// `second` is the default connection, living in $app['mongodb'] namespace
$app->register(new MongoDBServiceProvider(), [
    'mongodbs.options' => [
        'first' => [
            'uri' => 'mongodb://first.com:27017',
        ],
        'second' => [
            'uri' => 'mongodb://user:pass@second.com:27017/some_db',
        ],
        'third' => [
            'uri' => 'mongodb://third.com:27017,mongodb://third.com:27018?replicaSet=myReplica',
        ],
    ],
    'mongodbs.default' => 'second',
]);
```

**Usage**

```
// 'second' is default now
$second = $app['mongodb'];

// OR
$second = $app['mongodbs']['second'];

// OR even
$second = $app['mongodbs']['default'];
```

### Explicit set default connection - connection label

[](#explicit-set-default-connection---connection-label)

**Container setup**

```
// `second` is the default connection, living in $app['mongodb'] namespace
$app->register(new MongoDBServiceProvider(), [
    'mongodbs.options' => [
        'first' => [
            'uri' => 'mongodb://first.com:27017',
        ],
        'default' => [
            'uri' => 'mongodb://user:pass@second.com:27017/some_db',
        ],
        'third' => [
            'uri' => 'mongodb://third.com:27017,mongodb://third.com:27018?replicaSet=myReplica',
        ],
    ],
]);
```

**Usage**

```
// 'default' is... well, default
$second = $app['mongodb'];

// OR
$second = $app['mongodbs']['default'];
```

### Assemble `uri`

[](#assemble-uri)

**Container setup**

```
// resulting in uri: 'mongodb://username:password@example.com:27017/some_db'
$app->register(new MongoDBServiceProvider(), [
    'mongodb.options' => [
        'host' => 'example.com',
        'port' => '27017',
        'username' => 'user',
        'password' => 'pass',
        'database' => 'some_db',
    ],
]);
```

Few things to keep in mind here:

- `host` and `port` are required in this configuration scenario, no defaults fallback
- if you provide `username`, `password` is required
- `database` is optional in all cases

### Container namespace

[](#container-namespace)

By default, this service provider is registered in `mongodb.*` and `mongodbs.*` container namespace. While reserved by the [core parameters](http://silex.sensiolabs.org/doc/master/services.html#core-parameters) and [core services namespace](http://silex.sensiolabs.org/doc/master/services.html#core-services) is something everyone must live with, I don't feel occupying namespace (e.g. `mongodb`) from thrid party service providers is a good practice. Exactly this bad feeling made me implement feature (that I personally call) `service provider namespace`. The logic behind it is extremely simple - you provide single and multi namespace values (following the logic of core `DoctrineServiceProvider` which takes `db` and `dbs` namespaces) to the service provider constructor as respectively first and second argument.

It's a 'behind the scenes' feature, you may or may not use it but most important - you have a choice.

**Example - occupy `db` and `dbs` namespaces - given there is no registered `DoctrineServiceProvider`, no space for RDBMS!**

```
$app->register(new MongoDBServiceProvider('db', 'dbs'), [
    'db.options' => [
        'uri' => 'mongodb://example.com:27017',
    ],
]);
```

**Usage**

```
// namespace now is `db`
$mongo = $app['db'];

// ... and `dbs`
$mongo = $app['dbs']['default'];
```

**Example - override only single connection namespace to `db`**

```
$app->register(new MongoDBServiceProvider('db'), [
    'db.options' => [
        'uri' => 'mongodb://example.com:27017',
    ],
]);
```

**Usage**

```
// namespace now is `db`
$mongo = $app['db'];

// but multi connection namespace is still `mongodbs`
$mongo = $app['mongodbs']['default'];
```

MongoDB Client service factory
------------------------------

[](#mongodb-client-service-factory)

If you, for any reason (unknown to me!) decide you need to manually create `\MongoDB\Client` instance, you may use the registered with `MongoDBServiceProvider` factory callable.

```
$app->register(new MongoDBServiceProvider());

// somewhere else
$app['myStrangeMongoDBClient'] = function ($app) {
    return $app['mongodb.factory']()
}
```

Factory callable accepts one argument - array of connection configuration options, as they are passed via `mongodb.options` to the service provider. If no configuration options are passed, `$app['mongodb.default_options']` will be used (and you may override it!).

Configuration options, service parameters and services reference
----------------------------------------------------------------

[](#configuration-options-service-parameters-and-services-reference)

### Configuration options

[](#configuration-options)

The following describes the options passed to the `register()` container method (see examples section).

**Single connection options**

`mongodb` is the single connection configuration namespace, it may be overridden (see Namespace section). If this happens, you have to substitute it in the examples below.

- `mongodb.default_options` (`array`) - options used for zero configuration (or the factory service) in same format as `mongodb.options`. You may override it directly in your bootstrap code to change default behaviour. The default value of this option:

```
'mongodb.default_options' => [
    'uri'            => null,
    'host'           => 'localhost',
    'port'           => 27017,
    'database'       => null,
    'username'       => null,
    'password'       => null,
    'uri_options'    => [],
    'driver_options' => [
        'type_map' => [],
    ],
];
```

- `mongodb.options` (`array`) - same format as `mongodb.default_options`, set your single connection options - more details about `uri` format, uri and driver options in [MongoDB PHP library \\MongoDB\\Client documentation](http://mongodb.github.io/mongo-php-library/classes/client/) and [Official MongoDB `conection uri` documentation](https://docs.mongodb.com/manual/reference/connection-string/).

**Multi connection options**

`mongodbs` is the multi connection configuration namespace, it may be overridden (see Namespace section). If this happens, you have to substitute it in the examples below.

- `mongodbs.options` (`array`) - array of `mongodb.options` in format `LABEL => mongodb.options`. More details in the examples section.
- `mongodbs.default` (`string`) - connection label, defined in `mongodbs.options` to be set as default (thus retrieved with `$app['mongodb']`).

### Services

[](#services)

Retrievable in your code via `$app['SERVICE_NAME']`;

- `mongodb` (`\MongoDB\Client`) - default mongodb client. The name of this service depends on the single connection configuration namespace.
- `mongodbs` (`Pimple\Container`) - contains all mongodb clients registered with the service provider. Retrieve them by label. The name of this service depends on the multi connection configuration namespace.

**Internal**

- `mongodb.factory` (`callable`) - `\MongoDB\Client` factory service. The name of this service depends on the single connection configuration namespace.
- `mongodb.options.init` (`callable`) - used internally to one-time prepare the configuration array. The name of this service depends on the single connection configuration namespace.

### Parameters

[](#parameters)

Retrieve or override in your code via `$app['PARAMETER_NAME']`;

- `mongodb.default_options` (`array`) - set to override zero configuration setup &amp; mongodb client factory default behaviour. More details in `Configuration options` section. The name of this parameter depends on the single connection configuration namespace.

Tests
-----

[](#tests)

Run `phpunit` test after composer install

```
$ composer install && bin/phpunit

```

You may also print the coverage

```
bin/phpunit --coverage-text

```

Gotchas
-------

[](#gotchas)

- `s` is important! Be sure not to mess up `mongodb.options` and `mongodbs.options`
- It seems your service provider configuration is not found? In most cases you did the following - you have changed the [service provider namespace](#container-namespace), but you have provided the default namespace configuration options (e.g. `mongodb.options` instead `yourNamespace.options`)
- If you see `\LogicException` after you call the mongodb client in your code, check your service provider configuration - most probably you have provided both `mongodb.options` and `mongodbs.options` configuration parameters (which is clearly illegal).
- You have set 'default' connection in multi connection setup, but it is NOT the default one! Well, hardly, but you may double check if you are using both methods of setting default connection - connection labeled 'default' and `mongodbs.default = connection_name`. Connection label has higher precedence, so in the previous scenario, 'default' labeled connection will be the one returned by `$app['mongodb']` and `$app['mongodbs']['default']`

Contribute
----------

[](#contribute)

Fork me and open a Pull Request. Please don't provide code contribution without test coverage. Single commit Pull Request preffered.

Resources
---------

[](#resources)

- [Official MongoDB PHP library documentation](http://mongodb.github.io/mongo-php-library/)
- [Official MongoDB documentation](https://docs.mongodb.com/manual/)
- [Official MongoDB PHP extension (the new `mongodb` driver) documentation](http://php.net/manual/en/set.mongodb.php)
- [MongoDB\\Client - PHP library documentation](http://mongodb.github.io/mongo-php-library/classes/client/)
- [MongoDB Connection - official MongoDB documentation](https://docs.mongodb.com/manual/reference/connection-string/)
- [Silex Micro-framework](http://silex.sensiolabs.org/)
- [Google - everything else!](https://google.com/)

License
-------

[](#license)

This package is licensed under [MIT License](https://github.com/corllete/silex-mongodb-provider/blob/master/LICENSE)

(c) [Corllete](http://corllete.com/)

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Total

3

Last Release

3524d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/556697e55a9e4e64afffd64139109ccc67d12fe8a19f5370731c8311cf9ff327?d=identicon)[myovchev](/maintainers/myovchev)

---

Top Contributors

[![myovchev](https://avatars.githubusercontent.com/u/2827783?v=4)](https://github.com/myovchev "myovchev (16 commits)")

---

Tags

phpmongodbsilexmongoPHP Librarycorllete

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/corllete-silex-mongodb-provider/health.svg)

```
[![Health](https://phpackages.com/badges/corllete-silex-mongodb-provider/health.svg)](https://phpackages.com/packages/corllete-silex-mongodb-provider)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[denchikby/phalcon-mongodb-odm

Phalcon MongoDB ODM

4212.8k](/packages/denchikby-phalcon-mongodb-odm)[moriony/silex-mongo-provider

Mongo service provider for the Silex framwork.

118.5k](/packages/moriony-silex-mongo-provider)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
